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:

Read More
$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?

Related posts

Leave a Reply

5 comments

  1. Could this be your problem – as per the ‘special note’ on the documentation for the_date at http://codex.wordpress.org/Template_Tags/the_date:

    SPECIAL NOTE: When there are multiple posts on a page published under the SAME DAY, the_date() only displays the date for the first post (that is, the first instance of the_date()). To repeat the date for posts published under the same day, you should use the Template Tag the_time() or get_the_date() (since 3.0) with a date-specific format string.
    Use to add the date set in the admin interface.

    So use get_the_date, as documented here: http://codex.wordpress.org/Template_Tags/get_the_date

    For example

    if (get_the_date('j') > ($today-3)) :

    etc.

  2. 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;