Can't get my checkbox for metafield set true by default.
Everything is working fine, except default value.
I know there is a lot of questions and answers for it,
But I tried everything and still can't get it.
Here is my code:
function theme_add_meta_box() {
add_meta_box( 'theme_post_sidebar_option', esc_html__( 'Additional Options', 'theme' ), 'theme_post_sidebar_settings', 'post', 'normal', 'high' );
}
add_action( 'add_meta_boxes', 'theme_add_meta_box' );
Then my options:
function theme_post_sidebar_settings($post) {
$sidebar = get_post_meta($post->ID, '_theme_post_meta_sidebar', true);
wp_nonce_field( 'theme_update_post_sidebar_settings', 'theme_update_post_sidebar_nonce' );
?>
<input type="checkbox" name="theme_post_meta_sidebar_field" id="theme_post_meta_sidebar_field" value="1" <?php checked($sidebar); ?> />
<label for="theme_post_meta_sidebar_field"><?php esc_html_e( 'Sidebar', 'theme' ); ?></label>
<?php
}
Then my save function:
function theme_save_post_sidebar_settings($post_id, $post) {
$edit_cap = get_post_type_object( $post->post_type )->cap->edit_post;
if( !current_user_can( $edit_cap, $post_id )) {
return;
}
if( !isset( $_POST['theme_update_post_sidebar_nonce']) || !wp_verify_nonce( $_POST['theme_update_post_sidebar_nonce'], 'theme_update_post_sidebar_settings' )) {
return;
}
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
if(array_key_exists('theme_post_meta_sidebar_field', $_POST)) {
update_post_meta(
$post_id,
'_theme_post_meta_sidebar',
sanitize_text_field($_POST['theme_post_meta_sidebar_field'])
);
} else {
update_post_meta(
$post_id,
'_theme_post_meta_sidebar', null);
}
}
add_action( 'save_post', 'theme_save_post_sidebar_settings', 10, 2 );
Can someone help me, please?