Reverse Post Order For Category Archive

In this tutorial, i’ll provide the most efficient solution which enables you to change the order of posts in one or all category archives from ascending to descending.

A forum member asked this question:

I’m looking for a way to print one of my categories in ascending chronological order while leaving all others descending.

I’m only just starting out with PHP, so forgive any goofy errors. I found the following code somewhere online (the category in question is ID 8):

The solution they posted included query_posts which you should NOT use as its a highly inefficient way to modify a loop as explained by the lead Developer of WordPress Andrew Nacin some time ago.

Note: This function (query_posts) isn’t meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination). Any modern WP code should use more reliable methods, like making use of pre_get_posts hook, for this purpose. Source Codex

The Most Efficient Solution

Please copy ALL the code from the view raw link in the Gist and paste it at the end of your child themes functions.php file using a text editor like Notepad++.

The above code displays all posts in category-8 from oldest to newest meaning the oldest posts will be displays at the top if the first page in the category archive.

Simply change ASC to DESC to display posts on your category archives from latest to oldest.


Comments

5 responses to “Reverse Post Order For Category Archive”

  1. Thank you so much. This is exactly what I needed and it worked perfectly. Really appreciate you posting it.

  2. Douglas Barnes Avatar
    Douglas Barnes

    Cracked that nut. Thanks for you consideration and this code snippet in any event!

    1. Brad Dalton Avatar
      Brad Dalton

      Good stuff Doug!

  3. Perfect solution for an events category page using future-dated posts. Thanks.

  4. Oh great! This is what I need for.

Leave a Reply

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.