Group posts by date in Wordpress

2019-02-19 15:14发布

问题:

I need to write a WordPress query to accomplish the following - I am working on a site which has 40-50 posts daily - I want to show the posts "grouped" by date.

e.g.

20 March 2012
 post 1
 post 2
 post 3

19 March 2012
 post 4
 post 5
 post 6

Should I use more than 1 query to accomplish this, is it possible to do this without having to write custom SQL query.

I want the posts grouped.

回答1:

Yes it is possible:

$args = array('posts_per_page' => -1, 'orderby' => 'date' );

$myQuery = new WP_Query($args);

$date = '';

if ( $myQuery->have_posts() ) : while ( $myQuery->have_posts() ) : $myQuery->the_post();

if ( $date != get_the_date() ) {
    echo $date;
    echo '<hr />';
    $date = get_the_date();
}

the_title(); // or whatever you want here.
echo '<br />';

endwhile; endif;
wp_reset_postdata();

More info on the query here: http://codex.wordpress.org/Class_Reference/WP_Query