wordpresscheckbox

Check custom meta checkbox if it's checked Wordpress


    // Checkbox Meta
add_action("admin_init", "checkbox_init");

function checkbox_init(){
  add_meta_box("checkbox", "Checkbox", "checkbox", "post", "normal", "high");
}

function checkbox(){
  global $post;
  $custom = get_post_custom($post->ID);
  $field_id = $custom["field_id"][0];
 ?>

  <label>Check for yes</label>
  <?php $field_id_value = get_post_meta($post->ID, 'field_id', true);
  if($field_id_value == "yes") $field_id_checked = 'checked="checked"'; ?>
    <input type="checkbox" name="field_id" value="yes" <?php echo $field_id_checked; ?> />
  <?php

}

// Save Meta Details
add_action('save_post', 'save_details');

function save_details(){
  global $post;

if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
    return $post->ID;
}

  update_post_meta($post->ID, "field_id", $_POST["field_id"]);
}

I needed to add a custom meta checkbox on the posts page to enable certain content. The code above is from another stackoverflow answer. When I hit update post, it does save the check value, but I don't understand how to test if it's checked on a page I want to display the content.

doing if (isset()) tests if there is a value, so it's always returning true even if it's not checked. Is there a way I can test for the checked="checked" value? That is what is updating if I inspect element.


Solution

  • Check for on

    if($field_id_value == "on") $field_id_checked = 'checked="checked"';