$value
is always empty because post ID is missing. Pass the parameter ($post
object) to the hide_title_callback()
function and get the post ID right way.
Also, you should take care of nonces.
<?php
// pass the $post object
function hide_title_callback( $post ) {
// you have to verify this nonce inside `mysite_save_postdata()`
// https://codex.wordpress.org/Function_Reference/wp_nonce_field
wp_nonce_field( 'mysite_action_name', 'mysite_nonce_field_name' );
// now you have the post ID
$value = get_post_meta( $post->ID, '_mysite_meta_hide_title', true );
if( $value == "on" ) : ?>
<label for="hide">Hide: </label><input type="checkbox" name="hide" checked>
<?php else : ?>
<label for="hide">Hide: </label><input type="checkbox" name="hide">
<?php endif;
}
Verify the nonce
<?php
function mysite_save_postdata( $post_id ) {
// https://codex.wordpress.org/Function_Reference/wp_verify_nonce
if ( !wp_verify_nonce( $_POST['mysite_nonce_field_name'], 'mysite_action_name' ) ) {
return;
}
if ( isset( $_POST['hide']) ) {
update_post_meta(
$post_id,
'_mysite_meta_hide_title',
sanitize_text_field( $_POST['hide'] )
);
} else {
update_post_meta(
$post_id,
'_mysite_meta_hide_title',
sanitize_text_field( "off" )
);
}
}
To keep the database a bit cleaner I personally should not save the ‘off’ meta value. I should remove the _mysite_meta_hide_title
completely if checkbox is unchecked. So, it will exist if ‘on’ and do not if ‘off’. if()
statement in the hide_title_callback()
will remain intact.
<?php
if ( ! isset( $_POST['hide'] ) ) {
// unchecked
delete_post_meta(
$post_id,
'_mysite_meta_hide_title',
);
} else {
// checked
update_post_meta(
$post_id,
'_mysite_meta_hide_title',
'on' // nothing to sanitize here
);
}