I created a meta box with a value “home” of type checkbox, however I’m having hard times retrieving into the loop, I’m using this code into the loop:
<?php if(get_post_meta(get_the_ID(), 'home') == '1' ) : ?>
<!--BLABLA TO DISPLAY -->
<?php endif; ?>
if the checkbox is checked it should work like this, however is not… the most funny part is if I set it to ‘0’, it displays all the other pages where is not checked.
Any guess?
Thanks in advanced
UPDATE
Page Options code
$meta_boxes[] = array(
'id' => 'page-options',
'title' => __('Page Layout', 'andrewslab'),
'pages' => array('page'),
'context' => 'normal',
'priority' => 'high',
'fields' => array(
array(
'name' => __('Home', 'andrewslab'),
'id' => 'home',
'type' => 'checkbox',
'desc' => 'Display in <strong>home page</strong>',
'std' => ''
)
)
);
Template Code
<?php
global $wp_query;
$args = array_merge( $wp_query->query, array( 'post_type' => 'page' , 'showposts' => '4' ) );
query_posts( $args );
?>
<?php while (have_posts()) : the_post() ; $meta = get_post_meta( get_the_ID(), 'home', true ); ?>
<?php if( checked( $meta, 1, false ) ) : ?>
<!--BLABLA-->
<?php endif ?>
<?php endwhile; ?>
<?php wp_reset_query() ?>
Basically I need to enter into the loop only if the checkbox is checked.
You need to add the third parameter to
get_post_meta()
, soget_post_meta( get_the_ID(), 'home', true )
should at least get you closer. Just a note, in future, try doing avar_dump()
orprint_r()
on the variable(s) in the condition that are evaluating in an unexpected manner, if you’d done that here you would have seen that it was outputting an array, not the int/string you were expecting 🙂Checkboxes are a bit of a strange breed with respect to form data. They only get sent in the
$_POST
data if they are set. Your data-validation callback for saving custom post meta data should use anisset()
conditional as part of checkbox validation, and then set the value accordingly.Also, when you call
get_post_meta()
, the results are an array, so you’ll need to look at the first value of that array. I usually use something like this:After some research I was able to solve it… looks like it understands the values as ‘on’ and ‘off’… with this validation it works like charm
WordPress has a convenient way of doing this. There’s actually a
checked
(be sure to read the documentation) function built in that you can use. So for your example:And as @m0r7if3r said, you need to add
true
as the third argument toget_post_meta
.Not tested but should work.