0

Is there a way of getting all posts published on the latest date? It might not necessarily be today, it might be yesterday or the day before yesterday or even a day last week.

1 Answer 1

2

You can do it like this:

if ( have_posts() ) :
    /* Queue the first post, that way we know
     * which date we're dealing with.
     *
     * We reset this later so we can run the loop
     * properly with a call to rewind_posts().
     */
    the_post();

    // receive the latest post timestamp
    $latest_post_timestamp = strtotime( get_post()->post_date );

    /* Since we called the_post() above, we need to
     * rewind the loop back to the beginning that way
     * we can run the loop properly, in full.
     */
    rewind_posts();

    // create our custom query and set our latest date arguments
    $the_query = new WP_Query( array(
        'year' => date( 'Y', $latest_post_timestamp ),
        'monthnum' => date( 'm', $latest_post_timestamp ),
        'day' => date( 'd', $latest_post_timestamp ),
    ) );

    // render our latest date posts
    echo '<ul>';
    while ( $the_query->have_posts() ) :
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    endwhile;
    echo '</ul>';

    // Restore original query and post data
    wp_reset_query();
    wp_reset_postdata();
endif;
2
  • Plausible solution, but I think I'd run something similar on the pre_get_posts hook to reduce a little bit of overhead.
    – s_ha_dum
    Commented Jan 14, 2013 at 16:51
  • @Meshi then mark the answer as accepted by clicking on the tick under votes! Commented Jan 15, 2013 at 15:15

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.