I have a problem with displaying custom posts - I want each post to show only if a date set in a custom field has not passed.

I can't figure out the where I should put the if statement in the code. My idea is:

if($daysleft >= 0)
 then execute the while "custom post";

The following code is displaying the all the custom posts - both expired and not expired:

while(have_posts() ) : the_post();
$date = get_post_meta($post->ID, '_single_date', true); 
$daysleft = round( ($date-time()) / 24 / 60 / 60);  ?>

<div class="coupon-date">
if($date == '')_e('valid', 'Couponize');
else if($daysleft <= 0) _e('expired', 'Couponize'); 
else echo sprintf( _n('%d day left.', '%d days left.', $daysleft, 'Couponize'), $daysleft ); 

  • What values do you get for $daysleft when you debug the code?
    – Jebble
    Commented Jun 6, 2016 at 11:37

1 Answer 1


In your loop while(have_posts() ) : the_post(); you are unconditionally going through all posts, but since the loop stops after the_post() nothing actually happens. So that's where the condition has to go:

while(have_posts() ) {
    if ($daysleft >= 0) {
         ... other actions

Your code looks a bit incomplete to me, so I'm not sure if my exact code will work, but this definitely is where you want the condition.

Please note that if the query has returned, for instance, 15 posts you may have less displayed if some of them are expired. If you want a fixed amount displayed, you must not change the loop which displays the result of the query, but the query itself.

  • the_post() sets up the post for use inside the loop, it doesn't display it so the condition doesn't have to be set there, you wouldn't even want it because the condition needs the_post() to get the values.
    – Jebble
    Commented Jun 6, 2016 at 11:37
  • 1
    You're right. I've updated the answer.
    – cjbj
    Commented Jun 6, 2016 at 11:52

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.