order posts by date like craigslist

You may notice that I did more or less exactly this for Matt’s site: http://ma.tt. Every set of posts is grouped by the day. The basic principle is to keep track of your day in the loop, then print the date and related stuff only when it changes.

Take a basic Loop:

if ( have_posts() ) : while ( have_posts() ) : the_post();
  the_title();
  the_content();
endwhile; endif;

This just prints the title and content (without any formatting or anything) for everything in the current Loop. Now, you want it to pop out a new date every time the date changes. So you need to keep track of when it changes. Like so:

$loopday = '';
if ( have_posts() ) : while ( have_posts() ) : the_post();
  if ($loopday !== get_the_time('D M j')) {
    $loopday = get_the_time('D M j');
    echo $loopday;
  }
  the_title();
  the_content();
endwhile; endif;

What this does is to store the date that you’re wanting to output into a variable. Each pass through the loop, it gets it again and checks to see if it has changed. If it has not changed, then nothing happens. If it has changed, then it sets the variable with the new date string, outputs it, then moves on.

Obviously this is just an example. The specific details depend on how your existing loop works and how you want to output the information.

While it’s true that the_date() does this by default, sometimes it’s easier to do it yourself in this manner, for formatting reasons.

Leave a Comment