I’m trying to use custom meta boxes in wordpress. My goal at the moment is to create a meta box with a checkbox that I can use as a switch to turn on certain content. I’ve been scouring the web trying to piece together something that works, and so far I’ve gotten far enough to where I can generate a meta box with a checkbox, but the checked value isn’t carrying over to the loop for some reason. When I try to output the array to see if I can get anything out of it, it’s empty. I’ve looked at a ton of things and tried several meta box creation scripts, but I can’t get any of them to work. This method looked to be the most promising, but now I’m stuck. Is there something important I’m missing here? It’s as if the data isn’t being saved. Code included below:
Meta Box functions. Located in functions.php:
// 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];
echo '<label>Check for yes</label>';
$field_id_value = get_post_meta($post->ID, 'field_id', true);
if($field_id_value == "yes") {
$field_id_checked = 'checked="checked"';
}
echo ' <input type="checkbox" name="field_id" value="yes" '.$field_id_checked.' />';
}
// 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"]);
}
Code used to output content when checkbox is checked. This is also located in functions.php. The function is used in the loop.
function custom_content() {
if(isset($_POST['field_id']) && $_POST['field_id'] == 'yes') {
echo "It works!";
}
}
change your function on functions.php to
And your template, call it inside the loop like the ff: