Skip to main content
Generic filters
Search in title
Search in content
Search in excerpt

How to Display Posts Alphabetically with a WordPress Code Snippet

May 31, 2024
News

How to Display Posts Alphabetically with a WordPress Code Snippet

Published: May 31, 2024

You can use a WordPress code snippet to solve one of this CMS’ key limitations: sorting and displaying your content Posts alphabetically.

We think this issue is likely a challenge for many WordPress admins, so we decided to post our findings here as “News” and hopefully help anyone else solve the same problem for their site.

The WordPress Context

Our site is built using the WordPress CMS platform, which is terrific for many website-building needs. It provides a complete ecosystem of plugins and software features that enable us to customize this site precisely as we envision it.

However, WordPress lacks one essential feature: it defaults to displaying items in “reverse chronological” order and does not have a native option to change this behavior.  

Said differently, WordPress assumes you are running a “news” type site and that you want to show the most recent articles first. In our IT Dictionary scenario, we want to show topics alphabetically, which seems more productive and intuitive for scanning topic pages.

No Native Category Sort Options

It is hard to understand why WordPress, as a leading CMS platform, does not natively enable sort functions and configuration flexibility in this regard. For example, Joomla is another well-known and relatively popular CMS, and it has provided this core capability for many years, if not since its inception.

It is possible, though, to get Post sorting to work alphabetically in WordPress with some extra steps, and we now have this working correctly on this site.

A Code Snippet Solution

After trying other options, we believe the best solution is to insert a Code Snippet on the website’s front end so that all relevant requests are “pre-sorted” before being displayed to the readers.

Here is our code snippet, and we will clarify where this came from and how you can install it on your site:

function sort_posts_alphabetically_core_categories( $query ) {
    if ( is_admin() || ! $query->is_main_query() ) {
        return;
    }
    
    if ( is_category ( 'news-and-faqs', 'site-news', 'site-faqs' ) ) {
        $query->set( 'orderby', 'date' );
        $query->set( 'order', 'DESC' );
    }
	else {
        $query->set( 'orderby', 'title' );
        $query->set( 'order', 'ASC' );
	}
}
add_action( 'pre_get_posts', 'sort_posts_alphabetically_core_categories' );

Source of the Code Snippet

When looking around the Internet and various forums, you may find it challenging to find good information on showing WordPress posts alphabetically, and we certainly did.

We found the best starting point in the second answer on this page:

https://wordpress.stackexchange.com/questions/413555/how-to-sort-posts-alphabetically-based-on-a-specific-parent-category

How Does the Code Snippet Work?

The code’s concept is quite simple. The first line gives the code a name, and the last line adds this code to a WordPress feature called “pre_get_posts.”

This means the code snippet will be performed as part of every query lookup of Posts in your WordPress database. Note that the WPCode Code Snippet plugin (discussed below) can be set to run this code only on the Front End, which we did.

The code section that starts with “if ( is_admin()” says:

“If you are doing a Post query in the Admin side of the picture, do nothing”.

This means that Posts will show in the regular sort order from new to old in your Admin panel, which is how we want this to work. So, this part of our code is the same as in the original snippet on StackExchange.

We modified the next section to have “two sides” with different sorting of Posts for each one. We added the “else” part here to make this split happen, which enabled us to define a parent category and two subcategories as having the classic sort and all other categories as having the alphabetical sort.

Code Snippet Installation

We will walk you through the steps to set this up.

Step 1: Install the WPCode plugin on your site. Their general website is here: https://wpcode.com

You can add their free plugin through the Plugins area of your website’s Admin Panel and then activate it using the usual steps. The free plugin works well for our needs!

Step 2: In your Admin Panel menu, you can now navigate to the new menu item for Code Snippets and its main snippet dashboard.

Step 3: Click the Add Snippet button and select “Add Your Custom Code (New Snippet)”. This will create a new entry where you will put your snippet code. Give your snippet a name in the “Add Title for Snippet” bar. We called ours “Sort Terms Category Posts”.

Step 4: Select “PHP Snippet” on the top right as the Code Type so your snippet will be executed correctly.

Step 5: Copy the code snippet from this page into the Code Preview area.

Step 6: Modify the category names in the snippet to match the ones on your site that you still want to sort in the WordPress standard “new to old” way. You can add more names by adding a comma followed by another category name in quotes, as in our snippet with ‘news-and-faqs’, ‘site-news’, and ‘site-faqs’.

The “category names” here are, of course, the “slugs” they have. You can see these in your site’s URLs or Admin Panel for each category.

All other non-specified categories will be sorted alphabetically because of the ‘title’ and ‘ASC’ parameters for the ‘orderby’ and ‘order’ functions.

Step 7: Under the Location area, select Front-End Only, which is visible when you are in the Global area of the Location options.

Step 8: Click the Save Snippet button and then the Activate button to activate your site’s code.

Step 9: Check the front end of your site to see if the code snippet is now successfully displaying Posts in the sort order you are expecting!

Other Options We Looked At

We looked at many options, but the key ones included:

  • Using dynamic content features of our template
  • Using Plugins that provide “sort” options
  • Changing Publication Dates for Posts to force a sort order

We will share more details about each alternative option and why they did not work for our situation.

Using Dynamic Content Features of the Template

Our site template has powerful features for displaying “dynamic content” on pages. We experimented with this approach but found that “pre-sorting” Posts in this manner was not compatible with the filtering features of our IT Dictionary.

Your situation may differ entirely, so checking your template for “dynamic content” features would be worthwhile.

For example, our Recent Posts page is a one-page template that displays the “most recent 48 topics based on their modification date”. The template’s sorting capabilities are perfect for this situation and make the page configuration easy.

However, the same dynamic content options cannot co-exist nicely with the filter features on our IT Dictionary category pages because the filters would no longer work correctly.

So, this was a non-starter as an overall “alpha sort” solution in our case, but it is the first thing to check out for your site if you use a template with a dynamic content feature.

Plugins that Sort Things

A few Plugins enable sorting Posts in categories, which you can find on WordPress.org under Extend. We generally have two hesitations with these options:

1) We only want to use widely used and well-supported WordPress plugins. That way, we lower our risks and avoid making our site dependent on something that may not be available or maintained in the future. We have learned this the hard way with software in other situations, and it is no fun when that happens.

2) We only want to use a Plugin if it seems clear what it is doing and that it is “safe”. It is unclear to us how some of these “sort plugins” work or if they update anything in the database, which we would not want to have happen. Maybe they also work with a code snippet method, but we prefer the “self-managed” code snippet approach we describe here, where it is clear what it is doing “under the hood”.

Some “sort” plugins allow you to manually sort Posts in the Admin Panel by dragging them in the correct order. Given the number of topics we expect to have on our site eventually, any manual sorting process is not a practical solution for our situation.

Tinkering with Publication Dates

One method for displaying Posts in “alphabetical” order is to manually modify the Publication dates of Posts so that the default “new to old” sort also happens to be “from A to Z.”

As a matter of principle and due to the large number of Posts that our site will eventually have, we saw this option as a complete non-starter. It is not only manual, but we do not want to disrupt the proper recording of dates when we publish articles. We want the Publication and Modification dates to be accurate.

Conclusion

The code snippet we share here works as we envisioned: it nicely sorts the IT Dictionary topics alphabetically in all situations and does not interfere with the filter functions and features. The Sorting Widget on the IT Dictionary pages also works correctly, which can be handy for users.

The code snippet is easy to implement and customize for the categories that should be excluded from the “alpha sort”.

Another essential benefit of this approach is the ability to “uninstall” the alphabetical sort feature without any adverse impact. If you want to return to WordPress’ default behavior, you can easily deactivate the snippet, remove it entirely, or remove the WPCode plugin.

We also believe this is a viable long-term solution, as we assume that the core WordPress functionality it relies on will continue to be available in future WordPress versions. It certainly has been for a long time, and it would seem odd if this feature were to be removed in future versions of the CMS platform.

In summary, this method for alphabetically sorting Posts in WordPress works well and is easy to accomplish. We hope you find value in this write-up as you explore this feature for your website!