This website uses cookies to allow us to see how the site is used. If you continue to use this site, we assume that you are okay with this. If you want to use the sites without cookies, please see our privacy policy.

Group recent WordPress posts by date published

On a news site, it’s often helpful to group posts in reverse chronological order, with a date heading for all articles that were published on that date. You can achieve that with this snippet:

<?php $my_query = new WP_Query( array( 'showposts' => 20, 'post_type' => 'news' ) );
while( $my_query->have_posts() ): $my_query->the_post();
	$i = get_the_date( 'F j, Y' );
	if ($i == $j):
		// do nothing
	else :
		if ( $k == 1 ): ?>
		<?php endif; 
		$j = $i;
		$k = 1; ?>
		<h4><?php echo $i; ?></h4>
	<?php endif; ?>
		<span class="news-title">
			<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
<?php endwhile; ?>