Герб Укріїни
Believe in Ukraine and the Armed Forces. Glory to Ukraine!

How to Sort WordPress Post Archives in Ascending Order?

To change the sorting order in a WordPress category, you need to add the following code to the functions.php file:

As a result, new posts will appear at the bottom, not the top of the archive.

For example, post #1 was added later than #2, but it is correctly positioned in the first place.


This code is a PHP script fragment designed to change the way posts are sorted in a category on a WordPress site. Let’s delve into what this code does and how it can be useful.

Code Purpose: The purpose of this code is to change the sorting order of posts in an archive (category) page where posts of a specific category or tag are displayed. By default, WordPress sorts posts in reverse chronological order, meaning that new posts appear at the top. By using this code, you can change the sorting order so that new posts appear at the bottom.

Читайте також:  Development of Internet Projects at DiGrand

How It Works: The code defines a function sort_archives that will be called when processing queries to the WordPress database. Inside the function, the following happens:

  1. if ( ! is_admin() && $query->is_main_query() && is_archive() ): This condition checks that the current query is not administrative (i.e., not related to the WordPress admin panel), that it is the main query (not a nested query), and that we are on an archive page (category or tag).
  2. $query->set( ‘order’, ‘ASC’ );: If all the above conditions are met, this code sets the post sorting order to “ASC,” which stands for “ascending.” This changes the sorting order from reverse chronological to chronological, where newer posts will appear at the bottom of the page.
  3. add_action( ‘pre_get_posts’, ‘sort_archives’ );: Here, we hook the sort_archives function to the pre_get_posts hook, allowing our function to run before WordPress retrieves posts from the database for display.

Why It’s Useful: This code is useful if you need to change the display order of posts on an archive page in WordPress. For instance, if you want older posts to remain at the top and new ones to be added at the bottom, making your content appear more structured. This can be beneficial for certain types of websites, such as blogs or news portals, where maintaining a chronological order is important.
It’s essential to note that to use this code, you need access to the functions.php file of your WordPress theme and should be cautious when making changes to your site’s code, as improper PHP code manipulation can lead to errors or issues on your site. It’s also recommended to create regular backups of your site before making such changes.

Читайте також:  How to display attributes on the product page in WooCommerce, under a short description

Leave a Reply

Your email address will not be published. Required fields are marked *