2

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);
  • please show all the relevant code (save hook function, metabox hook function), not just small pieces of it. – Mark Kaplun May 31 '16 at 13:11
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;}

    ...
  • Sorry, this code does not work. when the post is open as a new post, then the value of $aps_display_post_title is 'no' because the update function run when post is created or updated, so default value is saved automatically.. so the checkbox is not marked by your condition. because ('no' != 'no') means false. so Checkbox is not marked by default. – Kamal Ahmed May 31 '16 at 17:21
  • where is the update function run when the "post is created"? when a new post edit page is loaded the value will not be set yet so '' != 'no' and the box will be checked. and when created/updated it will save as yes or no and therefore be checked or unchecked as set. – majick Jun 1 '16 at 5:47
  • the 'save_post' action hook runs when a post is created or updated. and the function to save the meta data is hooked into this 'save_post' hook. SO, when a post is NEWLY created or just Opened then the function to save the metadata automatically runs. so a default value is saved in the database, in this case, the default value is 'no'. So, when you check in new post screen, it become 'no' != 'no' which means false. Please kindly try to make a checkbox checked by default in a metabox then you can see the problem. Thank you so much. – Kamal Ahmed Jun 1 '16 at 9:34
  • ah gotcha now, check updated answer to hook to edit_post instead – majick Jun 1 '16 at 13:28
  • 1
    Thank you a million man. You are awesome. :) It is working. the edit_post hook is the key to this success :) . Thank you again for your kind help. – Kamal Ahmed Jun 1 '16 at 13:48
0

Your code will make the value yes only when the user fills the form. You could check if the meta is not there then make it checked, or try this:

$aps_display_post_title = get_post_meta( $post->ID, 'aps_display_post_title', true );
$aps_display_post_title = ! ( 'off' == (string) $aps_display_post_title );

?>
    <input type="checkbox" name="aps_display_post_title" <?php checked( $aps_display_post_title ); ?> />
<?php


// updating the meta
$aps_display_post_title = ! empty($_POST['aps_display_post_title'])? 'on' : 'off'; // call this only when the checkbox is in the screen
update_post_meta( $post_id, "aps_display_post_title", $aps_display_post_title );

Guess it should be working. BUT don't call the updating script if the checkbox is not in the form in the screen, that will uncheck the boxes even if checked..

  • Sorry, This code does not work. Actually the problem is that I have only two values. and the save_post runs when the post is created or updated. So, in my case, a default meta data is saved when the post is just created but not saved. Lets, talk about your code, when the post is open as new post then the value of $aps_display_post_title will be 'off' by default. then you turn it in to boolean false by this "! ( 'off' == (string) $aps_display_post_title );" then you use checked() function. the function does not check the box because the value is false. So, I have not got the expected result. – Kamal Ahmed May 31 '16 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.