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 );
}
You should use
delete_post_meta( $post->ID, 'show_links' );
instead ofdelete_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 callget_post_meta
. So this should solve your problem: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”)