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 ): ?>
			</ul>
		<?php endif; 
		$j = $i;
		$k = 1; ?>
		<h4><?php echo $i; ?></h4>
		<ul>
	<?php endif; ?>
	<li>
		<span class="news-title">
			<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
		</span>
	</li>
<?php endwhile; ?>
</ul>

https://gist.github.com/theukedge/a0f5c4e9a572820d103e

Image: http://min.us/i/2sWDseCCYTWr