how to set default value for checkbox in wordpress

I am facing a problem to set default value for the checkbox field in WordPress.
I have a checkbox input field (metabox) in a custom post. I want the checkbox to be checked by default. and if user uncheck it then it should be saved and unchecked and remain unchecked when page is refreshed. My problem is that I can not set the default value for the checkbox. I have only two values to work with. Main problem arises, because the savemetadata function runs when I click ‘add new’ post, So, a default value gets saved in the database automatically without saving the new post. I have been trying for 3 days now. I have tried to save a default value ‘yes’ when user does not check the checkbox.

but in that case, when user does uncheck then still it become checked with the default value.
my current code snippet

// for displaying metabox
function aps_add_meta_box() {
 add_meta_box(
    'aps_metabox',
    __( 'Slider Settings & Shortcode Generator', APS_TEXTDOMAIN ),
    'aps_metabox_cb', // callback
    'apspostslider', // screen or posttype
    'normal'
 );}
add_action( 'add_meta_boxes', 'aps_add_meta_box' );

function aps_metabox_cb( $post ) {
    wp_nonce_field( 'aps_meta_save', 'aps_meta_save_nounce' ); // nounce
    $aps_display_post_title = get_post_meta( $post->ID, 'aps_display_post_title', true );

    <input type="checkbox" name="aps_display_post_title" value="yes" <?php checked( $aps_display_post_title, 'yes'); />
}

The code for saving metabox data in the save fucntion:

function aps_meta_save( $post_id ) {
    // Perform checking for before saving
    $is_autosave = wp_is_post_autosave($post_id);
    $is_revision = wp_is_post_revision($post_id);
    $is_valid_nonce = (isset($_POST['aps_meta_save_nounce']) && wp_verify_nonce( $_POST['aps_meta_save_nounce'], 'aps_meta_save' )? 'true': 'false');

    if ( $is_autosave || $is_revision || !$is_valid_nonce ) return;
   // Is the user allowed to edit the post or page?
    if ( !current_user_can( 'edit_post', $post_id )) return;
    $aps_display_post_title = (isset($_POST['aps_display_post_title']))? sanitize_text_field( $_POST["aps_display_post_title"] ): '' ;

    update_post_meta($post_id, "aps_display_post_title", $aps_display_post_title);
}
// save only when aps post slider posttype is saved
    add_action( 'save_post_apspostslider', 'aps_meta_save');

I have tried the following code while saving but in that case the checkbox is checked by default. but when I uncheck and save the post, then checkbox remained checked.

    $aps_display_post_title = (isset($_POST['aps_display_post_title']))? sanitize_text_field( $_POST["aps_display_post_title"] ): 'yes' ;

    update_post_meta($post_id, "aps_display_post_title", $aps_display_post_title);

UPDATE:
Now everything is working after changing the hook. the save_post hook runs when a post is newly created or updated. SO, the function to save the meta data would run when a post is created and thus a default value would be saved in the database. However, now after changing the hook to -“edit_post”, now everything works. Thanks to the brother majick who helped me. All working code is given below:

//Show meta box
function aps_add_meta_box() {
add_meta_box(
    'aps_metabox',
    __( 'Slider Settings & Shortcode Generator', APS_TEXTDOMAIN ),
    'aps_metabox_cb',
    'apspostslider',
    'normal'
);
}
add_action( 'add_meta_boxes', 'aps_add_meta_box' );

/**
 * Prints the box content.
 */
function aps_metabox_cb( $post ) {


    // Add a nonce field so we can check for it later.
    wp_nonce_field( 'aps_meta_save', 'aps_meta_save_nounce' );
    $aps_display_post_title = get_post_meta( $post->ID, 'aps_display_post_title', true );
    <input type="checkbox" name="aps_display_post_title" value="yes" <?php if ($aps_display_post_title != 'no') { echo 'checked'; }?>/>

}

// Save or Update metabox data
function aps_meta_save( $post_id, $post ) {

if ($post->post_type != 'apspostslider') {return;}
// Perform checking for before saving
$is_autosave = wp_is_post_autosave($post_id);
$is_revision = wp_is_post_revision($post_id);
$is_valid_nonce = (isset($_POST['aps_meta_save_nounce']) && wp_verify_nonce( $_POST['aps_meta_save_nounce'], 'aps_meta_save' )? 'true': 'false');

if ( $is_autosave || $is_revision || !$is_valid_nonce ) return;
// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post_id )) return;

 if ( (isset($_POST['aps_display_post_title']))
         && ($_POST['aps_display_post_title'] == 'yes') ) {
        $aps_display_post_title="yes";
} else {$aps_display_post_title="no";}

    update_post_meta($post_id, "aps_display_post_title", $aps_display_post_title);

add_action( 'edit_post', 'aps_meta_save', 10, 2);

2 Answers
2

I think the problem might could be the logic with using checked

 <input type="checkbox" name="aps_display_post_title" value="yes" <?php if ($aps_display_post_title != 'no') {echo 'checked';} ?> />

…on the other hand then running sanitize_text_field on the checkbox value might also be causing the problem.

Instead you might want to break the logic down differently so it is easier to understand, and use this with the code above which checked that the value is not no and so will default as checked:

if ( (isset($_POST['aps_display_post_title'])) 
  && ($_POST['aps_display_post_title'] == 'yes') ) {
    $aps_display_post_title="yes";}
} else {$aps_display_post_title="no";}

update_post_meta($post_id, "aps_display_post_title", $aps_display_post_title);

UPDATE

To prevent the metasave function from firing on post creation, hook to edit_post instead of save_post (and do the post type check internally using the second argument passed which is $post)…

add_action( 'edit_post', 'aps_meta_save', 10, 2);

function aps_meta_save($post_id, $post) {

    if ($post->post_type != 'apspostslider') {return;}

    ...

Leave a Comment