Search code examples
wordpressdateloopssliderposts

WordPress the_date within the loop only returning one post


I have a custom template that is using the loop to grab post info to build a custom slider and it is working perfectly. The client gave a new requirement that they only want posts from the last 2 days to be displayed in the slider.

Within the loop I added the following if statement:

$today = date('j');

if ( have_posts() ) : 
while ( have_posts() ) : 
the_post();

// Added the below code
    if (the_date('j','','',FALSE)>($today-3)) : 

    // Builds slide

    endif;
// End of new code

endwhile; 

else: 
 ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php 
endif; ?>

When this code is added the loop only displays a single post, the first post which is found to meet this IF statement's condition, and does not display any others. I have manually changed the dates so that at least 3 posts have publish dates within the last two days, still nothing.

When I uncomment the above lines the code works fine and pulls all posts to be built into slides.

I cannot use the "posts_where" filter as this affects the other posts on the page (Imagine the slider at the top of the page, and posts below the slider).

Is there something I am missing? Or can the_date() not be used like this?


Solution

  • Don't ask why, and if you can explain why please do in the comments, but had to do something like this:

    $posts_date = $post->post_date;
    $two_days_ago = strtotime(date('Y-m-d H:i:s') . ' -2 day');
    if ($posts_date >(date('Y-m-d H:i:s', $two_days_ago))) : 
        //process code
    endif;