0

I want to save a meta with a checkbox for all my posts, here's my code :

add_action('save_post','save_metaboxes');
function save_metaboxes($post_ID){

if(isset($_POST['is_viewpay'])) {
    $old_meta = get_post_meta($post_ID, '_is_viewpay', true);

    if(!empty($old_meta)){
        update_post_meta($post_ID, '_is_viewpay', 'active');
    } else {
        update_post_meta($post_ID, '_is_viewpay', '');
    }
}

}

The problem is when I uncheck the checkbox and save my post, It always stay checked. I don't know why.

Thanks for your help !

1
  • Your code is updating the meta based on $old_meta being empty or not, instead of the submitted value... Commented Dec 12, 2017 at 13:03

1 Answer 1

2

You can use this to update your post meta

function save_metaboxes($post_ID){    
    if( isset($_POST['is_viewpay']) ){
        $featured = 1;            
    }
    else{
        $featured = 0;
    }
    update_post_meta( $post_id, '_is_viewpay',  $featured);
}

To make the checkbox checked, you can use something like this:

<?php $check = $featured ? 'checked':''; ?>
<input <?php echo $check; ?> name="is-viewcheck" type="checkbox" value="1"> Is view pay

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.