I think I was doing everything right but my data doesn't save. What is wrong with this code?
add_action( 'add_meta_boxes', 'niloyrudra_add_meta_boxes' );
add_action( 'save_post' 'save', 10, 2 );
function niloyrudra_add_meta_boxes() {
add_meta_box( 'niloy_meta_box', __( 'Additional Meta Boxes', 'impressive-child' ), 'niloyrudra_custom_field_callback', 'post', 'advanced', 'default' );
}
function niloyrudra_custom_field_callback( $post ) {
wp_nonce_field( 'niloy_meta_box_id', 'niloy_meta_box_nonce' );
$value = get_post_meta( $post->ID, '_niloyrudra_custom_field_key', true );
?>
<label for="my_new_field">
<?php _e( 'Description for this field', 'impressive-child' ); ?>
</label>
<input type="text" id="my_new_field" name="my_new_field" value="<?php echo esc_attr( $value ); ?>" size="25" />
<?php
}
function save( $post_id, $post ) {
/*
* We need to verify this came from the our screen and with proper authorization,
* because save_post can be triggered at other times.
*/
// Check if our nonce is set.
if ( ! isset( $_POST['niloy_meta_box_nonce'] ) ) {
return $post_id;
}
$nonce = $_POST['niloy_meta_box_nonce'];
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $nonce, 'niloy_meta_box_id' ) ) {
return $post_id;
}
/*
* If this is an autosave, our form has not been submitted,
* so we don't want to do anything.
*/
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return $post_id;
}
// Check the user's permissions.
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return $post_id;
}
// Sanitize the user input.
$data = sanitize_text_field( $_POST['my_new_field'] );
// Update the meta field.
update_post_meta( $post_id, '_niloyrudra_custom_field_key', $data );
}