WordPress Tutorial: Sorting Your Posts By Most Recently Modified or Updated

Andrei Marks · August 11, 2012

(Wordpress v3.4.1, Thematic v1.0.2.1)

Over on AM/Blog I have a number of posts set up as “Project” posts. They introduce various projects I’m working on and I use them to keep tabs on their statuses.

However, since they’re being updated asynchronously, ordering the posts by creation date really doesn’t make sense. I’d rather people see what I’ve been working on most recently, which might be a project that was started several weeks ago. This turned out to be a fairly easy thing to do, and I learned a little bit more about Thematic’s “add_action” function.

Step 1: The Code

The magic code is:

[php]query_posts(‘orderby=modified’);[/php]

This function is used to display different posts at a particular URL than would normally show up. I should note that the WP codex entry on this function does say that using the query_posts is “ the easiest, but not preferred or most efficient, way to alter the default query that WordPress uses to display posts.” But my personal blog is just a little site, so I don’t mind at the moment.

The “orderby” parameter (other parameters available here) controls what you think it does. It normally defaults to date.

But where to put the code?

Step 2: Functions.php

You want to put the query_posts call before the main loop starts, like in the example below:

[php]<?php

// The Query query_posts( $args );

// The Loop while ( have_posts() ) : the_post(); echo ‘<li>’; the_title(); echo ‘</li>’; endwhile;

// Reset Query wp_reset_query();

?>[/php]

Thematic utilizes a number of hooks that can be used to inject code into certain points of the theme’s code. This website runs through the different hooks, and this site even more helpfully visualizes the injection points for you.

Very handily, there is a hook called “thematic_above_indexloop” that can throw code right above the index loop, exactly where we want it.

Put the following code in your child theme’s functions.php file:

[php] function order_posts_by_modified() { query_posts(‘orderby=modified’); }

add_action(‘thematic_above_indexloop’, ‘order_posts_by_modified’);[/php]

So there are really two steps.

  1. Define the function that contains the code you want to inject. I did that in the "order_posts_by_modified" function.
  2. Call add_action() to load that code, by passing the hook name as the first parameter, and your newly defined function as the second.

That’s it! There are also more options than add_action, but for now we only need to add code. I also didn’t use wp_reset_query(), which is used to destroy the previous query. But if I were to use it I’d just do the same as above with the hook that injects code after the loop. Easy! But I’m lazy.

A miscellaneous thing I learned, make sure that your functions.php starts with an open “ <?php “ tag and leaves it open. Otherwise WordPress accidentally everything.

Useful Links:

Twitter, Facebook