The reason that the field is not saving is due to the nonce check in my_content_save()
failing. Changing the nonce check to the following code will fix the issue:
if (!wp_verify_nonce( $_POST['content_overview_nonce'], 'content_overview_save' )){
return;
}
The nonce check should use the content_overview_save
action because that is what was specified here:
wp_nonce_field( 'content_overview_save', 'content_overview_nonce');
Note that there was also a missing >
in the #page_content_overview_metabox
input field. For the sake of completeness, here’s the full updated code:
class my_metaboxes{
public function __construct() {
add_action( 'add_meta_boxes', array( $this, 'my_overview_metabox' ) );
add_action( 'save_post', array( $this, 'my_content_save' ) );
}
public function my_overview_metabox(){
add_meta_box(
'page_overview_metabox',
'Page content overview',
array( $this,'content_overview_metabox' ),
'post',
'advanced',
'high'
);
}
public function content_overview_metabox( $post ) {
wp_nonce_field( 'content_overview_save', 'content_overview_nonce' );
$value = get_post_meta( $post->ID, '_post_content_key', true );
echo '<input type="text" id="page_content_overview_metabox" name="page_content_overview_metabox" value="' .
esc_attr( $value ) . '" placeholder="Enter the page overview details" style="width: 100%; height:120px;">';
}
public function my_content_save( $post_id ){
if ( ! isset($_POST['content_overview_nonce'])){
return;
}
if ( ! wp_verify_nonce( $_POST['content_overview_nonce'], 'content_overview_save' ) ) {
return;
}
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
if ( !isset( $_POST['page_content_overview_metabox'] ) ) {
return;
}
$my_data = sanitize_text_field( $_POST['page_content_overview_metabox'] );
update_post_meta( $post_id, '_post_content_key', $my_data );
}
}
new my_metaboxes();