I have a function which display posts of a custom post type in wordpress:
Code:
<?php
$args = array(
'post_type' => 'todo_listing',
'posts_per_page' => 4,
'order' => 'asc',
'meta_value' => '0'
);
$loop = new WP_Query( $args );
?>
<ul class="leftlist">
<?php
while ( $loop->have_posts() ) : $loop->the_post();
?>
<li class="todo" id="<?php echo get_the_ID();?>" itemage="<?php echo get_post_meta(get_the_ID(),'_todotime',true)?>"><a href="javascript:;"<?php if($all_meta_for_user[get_the_ID()][0]){
?>
class="strike"
<?php
}
?>
>
<?php if($all_meta_for_user[get_the_ID()][0]){?>
<span class="check_box cb"></span>
<?php }else{?>
<span class="uncheck_box cb"></span>
<?php }?>
<p><?php the_title(); ?></p></a>
<?php
endwhile;
?>
</ul>
Which results in the HTML rendered as follows:
<li class="todo" id="1013" itemage=""><a href="javascript:;" class="">
<span class="cb uncheck_box"></span>
<p>Some Text here</p></a>
</li>
or
<li class="todo" id="1013" itemage=""><a href="javascript:;" class="">
<span class="check_box"></span>
<p>Some Text here</p></a>
</li>
If the class has span class="cb uncheck_box"
the meta value is 0 and if the span class="check_box"
, meta value is 1.
I only want to show those items with Meta Value 1. How can I modify the above wordpress function to achieve this?
Here is the code you can use:
<?php
$args = array(
'post_type' => 'todo_listing',
'posts_per_page' => 4,
'order' => 'asc',
'meta_value' => '0'
);
$loop = new WP_Query( $args );
?>
<?php
while ( $loop->have_posts() ) : $loop->the_post();
?>
<?php if(get_post_meta(get_the_ID(), 'checkbox_meta', true) == 0) { ?>
<?php echo get_the_ID();?> <?php the_title(); ?>
<?php } ?>
<?php
endwhile;
?>
I think there is some detail that you have missed to give out but assuming the code <?php echo get_the_ID();?> <?php the_title(); ?>
prints out the given html then I suppose this could work. Get back to me if it couldn't be solved.
You only need to do a small change to your query and it should be all fixed.
$args = array(
'post_type' => 'todo_listing',
'posts_per_page' => 4,
'order' => 'asc',
'meta_query' => array(
array(
'key' => 'checkbox_meta',
'value' => '1',
'compare' => 'IN',
)
)
);
$loop = new WP_Query( $args );
That takes the key checkbox_meta
and checks that it has a value of 1. If not then it doesn't get the data.
Therefore you should get the first 4 with the checkbox_meta
set to 1.
Readmore: http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters section 'orderby' with 'meta_value' and custom post type