How to get checkbox by default true in metabox?

To get checkbox by default true in metabox, You can use checked Attribute for checkbox. So i have made two changes in your code.

  • In option, I have added new condition, by default it will checked
    checkbox and if meta_value 1 , If updated value of meta_value is
    unchecked and not empty then it will uncheck checkbox.
  • In save Function, i have change value from null to unchecked.

So, by default checkbox will be checked, when you save with checked checkbox it will checked if you uncheck and save it will unchecked.

options function:

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' );

    $checked = 'checked';
    if($sidebar == 'unchecked' && !empty($sidebar))
    {   
        $checked = ''; 
    }
    ?>
    <input type="checkbox" name="theme_post_meta_sidebar_field" id="theme_post_meta_sidebar_field" value="1" <?php echo $checked;  ?> />
    <label for="theme_post_meta_sidebar_field"><?php esc_html_e( 'Sidebar', 'theme' ); ?></label>

    <?php
}

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', 'unchecked');
        }
    }
    add_action( 'save_post', 'theme_save_post_sidebar_settings', 10, 2 );