AZIndex LogoAsk and ye shall receive!

I have been going through the backlog of comments and noted that a couple of people wanted to sort their indexes in chronological order — i.e. they want the list of posts sorted by date with the most recent at the top.  So I was just pondering the issue, wondering if I should really add this feature even though it’s not really something AZIndex is designed to do, when I suddenly had “D’oh” moment…

You can already do this with the current release of AZIndex!  (By using a one-line custom compare function.)

Here’s how you do it:

  1. Go to the AZIndex management page (Manage >> AZIndexes) and create a new index.
  2. Set up your settings as usual, but also select the advanced option “Use a customized comparison function for sorting the index“.
  3. A new option field will appear where you can type in the name of the custom compare function you will be adding.  Type in “az_chronological_compare“.
  4. Save your changes.
  5. Now we need to add the compare function somewhere, and a good place for that is in the functions.php file of your current theme.  Go to Design >> Theme Editor.
  6. Look for a file called something like Theme Functions (functions.php) in the list on the right and click on the link to load it into the editor.
  7. Add the following function somewhere in the file:
    function az_chronological_compare($in1, $in2) {
        return $in1['id'] < $in2['id'];
    }

    IMPORTANT: The function must be between PHP start and end tags: i.e. somewhere between <?php and ?>.  If they don’t exist in the file, simply add them around the function.

  8. Click Update File at the bottom of the page to save your changes.
  9. Now go to the page created when you created the index and take a look.  The items in the index should appear in chronological order starting with the most recent. (If you want the oldest first, simple change the ‘<‘ for a ‘>‘.)

There are a few important things to consider about this solution:

  1. This method works because WordPress increments the post and page IDs by one every time a new post or page is created.  If, for any reason, the incremented ID was reset to a lower value then the posts will not appear in the expected order.  It is highly unlikely that has happened on your blog (probably a far less than 1% chance) because it is never done by WordPress itself, so in all probability this method will work just fine.
  2. There is absolutely no point in using the alphabetical headings or links options with this type of index.  In fact, the plugin will probably get hopelessly confused and generate some very strange looking output!  If you avoid using those options, you should be fine.
  3. I am not planning on adding any new features for chronological indexes (like month or year headings, etc).  I suspect there are other ways or other plugins that already do that type of archiving already.