1

I want to add a checkbox in the post meta and set it as checked by default. I am trying following code, but it does not display the checked box by default. However it saves correctly and after saving the post, it displays the checked box.

How can I set it checked by default?

<?php
    $checked = get_post_meta( $post->ID, 'show_links', true );  //returns string(0) "" 
    $current = true;
    $echo = true;
?>
<input name="show_links" type="checkbox"  value="1" <?php checked( $checked, $current, $echo ); ?>/>

This is how I'm saving the value:

if ( isset( $_POST['show_links'] ) && $_POST['show_links'] == 1) {
    update_post_meta( $post->ID, 'show_links', 1 ); 
} else {
    delete_post_meta( $post->ID, 'show_links', 1 ); 
}

1 Answer 1

1

You should use delete_post_meta( $post->ID, 'show_links' ); instead of delete_post_meta( $post->ID, 'show_links', 1 ); the last form is used to delete specific values when you have multiple values with the same key. Here you most probably already stored a value which is an empty string that you never deleted and that's what you get when you call get_post_meta. So this should solve your problem:

if ( isset( $_POST['show_links'] ) && $_POST['show_links'] == 1) {
    update_post_meta( $post->ID, 'show_links', 1 ); 
} else {
    delete_post_meta( $post->ID, 'show_links' ); 
}

However, the way you do it kind of forces the system to never remember the user chose not to "show links" and they will have to uncheck the box each time they change the post (which is different than "by default it's on")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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