4

I have 7 meta fields for a custom post type in Wordpress. These 7 in particular are days of the week (Sunday thru Saturday) and have checkboxes for each. I've successfully gotten the checkbox to POST when the value is "On", however when I return to the edit page and try to deselect, the value stays the same in the database.

Here is what I have for each item input:

 <li><input type="checkbox" name="sunday" <?php if( $meta_sunday == true ) { ?>checked="checked"<?php } ?>" /> Sunday<br /></li>

And my update lines:

if(!isset($_POST["sunday"])):
    return $post;
    endif;
    update_post_meta($post->ID, "sunday", $_POST["sunday"] );
  • If I'm not mistaken, an unchecked checkbox is not set in $_POST. You'd have to empty the meta for the checkboxes that are not set. – Shane Feb 7 '12 at 17:00
4

It appears the post meta is not being cleared for 'sunday' when the checkbox is unchecked.

If( isset($_POST['sunday']) ){
    update_post_meta($post->ID, "sunday", $_POST["sunday"] );
}else{
    delete_post_meta($post->ID, "sunday");
}
return $post;

Or you can set the value to false

If( isset($_POST['sunday']) ){
    update_post_meta($post->ID, "sunday", true );
}else{
    update_post_meta($post->ID, "sunday", false );
}
return $post;
  • Just consolidating your code a little, update_post_meta($post->ID, "sunday", isset($_POST['sunday']) ); – Matthew Boynes Feb 7 '12 at 22:14
  • Thanks @MatthewBoynes and Ryan Meier - this worked perfect – javy Feb 8 '12 at 14:37
2

Unchecked checkboxes are not set in the $_POST, so you'd have to empty their meta field.

Something like this should work :

 $sunday = ( isset( $_POST['sunday'] ) ) ? $_POST['sunday'] : "";
 update_post_meta( $post->ID, 'sunday', $sunday );
0

Unchecked checkboxes are not set in the $_POST, they are set in $_REQUEST, you can set checkbox value of custom post type like this:

if ( isset( $_REQUEST['inprint'] ) ) {
   update_post_meta($post_id, '_inprint', TRUE);
 } else {
   update_post_meta($post_id, '_inprint', FALSE);
 }

and get checkbox value like this:

global $post;

$inprint= get_post_meta($post->ID, '_inprint', true);

<input type="checkbox" name="inprint" value='1'<?php checked(1, $inprint); ?> />

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.