Here’s the simplest way to make a WordPress archive list alphabetically.

Why would you want to do this? A directory is the #1 reason.

This script is the base version. It simply sorts by the absolute first letter of the post title. Does that matter? It could if you’re talking about an archive of songs or books or movies. You don’t want to sort by articles (“a”, “an”, “the”). That’s a more complicated script. I’ll add it later.

STANDARD EDIT YOUR CODE AT YOUR OWN RISK DISCLAIMER

Whenever you edit your code, you risk breaking your site.

You should:

  • work on a copy of your site or a staging site. Working on a live site is playing with fire.
  • edit a child theme or put scripts in a custom plugin. Edits to the parent theme may be lost upon the next update.
  • edit the code via text editor so that you can quickly remove it if you break your site.
  • makes copies of anything you remove in case you need it.

The code

add_action( 'pre_get_posts', 'group_query',100 );
function group_query( $query ) {
	if ( ! is_admin() && ( $query->is_post_type_archive('directory') )) {
		$query->set('orderby', 'title');
		$query->set('order', 'ASC');
	} // end if
}

Making the code your own

This code can be added to your theme’s functions.php file or to a custom plugin.

This script uses the same idea as the script for changing the posts per page but uses different specifics. Here’s your homework:

  1. ! is_admin() && ( $query->is_post_type_archive(‘directory’)
    That tells WordPress when to run the script. This example is for a custom post type called directory. You need to change the bit after “->” to meet your needs. WordPress has a ton of conditional tags you can use.
  2. group_query
    That is the function name and is used twice. If you use this script more than once, you’ll need to rename the function. The name doesn’t really matter as long as it isn’t used by something else.
  3. $query->set(‘orderby’, ‘title’); $query->set(‘order’, ‘ASC’);
    The 1st bit says to order by title and the 2nd bit says which way to order it.

Photo by Marc Mueller