Interspersing your post listing with date headers in WordPress

Update: OK, so at least one person wanted it as a plugin, so feel free to download Intermittent Date Headers.

Here’s a code snippet that’s not really worth making into a plugin. It’s designed to put date headers into your main post listing page. As an example, you could end up with:

Heading: March, 2008
Post: dated 15th March
Post: dated 28th March
Post: dated 29th March
Heading: April, 2008
Post: dated 1st April
Post: dated 4th April

The function takes it’s degree of granularity from the date format you give it. So you can choose to have a month header, and each months posts below each header, or to have a daily header, and all of that days posts below each header. The parameters you pass are exactly the same as for the the_date template tag.

The code

Paste the code below into the functions.php file in your theme, if functions.php doesn’t exist then create it.

// For use on pages which list posts, and to be used within the_loop(). Outputs a
// date header to split up the post listings. See the_date() template tag docs for
// usage: http://codex.wordpress.org/Template_Tags/the_date
function intermittent_date_header( $d='', $before='', $after='', $echo = true )
{
global $idh_last_date_header;
// Get the current date
$date_header = the_date( $d, $before, $after, false );
// If it's the same, don't bother continuing
if ( $date_header == $idh_last_date_header ) return;
// Record the current date header as the last one
$idh_last_date_header = $date_header;
// Decide what to do, and do it. Return, or echo...
if ( ! $echo ) return $date_header;
echo $date_header;
}

Comments and questions welcome. (BTW, if people want this as a plugin, let me know.)

2 Responses to “Interspersing your post listing with date headers in WordPress”


  1. 1 Tom Smith

    Fab! I’ve ALWAYS wanted this and couldn’t believe it wasn’t standard. Thanks

  2. 2 Simon

    Hi Tom - I was worried about putting this snippet up, because it felt like I *must* have missed something and people would laugh and point at the obvious standard function to do it… I’m glad there’s someone to stand next to me when that finally happens. ;)

Leave a Reply