By default, WordPress sorts all post types chronologically by date, like regular posts. This is a good default, but not always the desired result for some post types. For instance, the tutorials on this site are not really date dependent, and therefore, it makes little sense to always show the latest one first. Instead, I sort all tutorials alphabetically, from A to Z.
To accomplish this, we’re going to use a hook in WordPress called pre_get_posts. The pre_get_posts hook allows us to modify how the WordPress query is structured in any given situation, but it’s best suited to making changes on archive pages. It can be used to exclude certain categories, only include content published within a certain date span, or change how the content of the query is ordered when it is output.
We’re doing the latter in the code below, which should go into the functions.php file of your theme. Replace xx with the slug for your project, and replace post_type_name with the name of the post type you want ordered alphabetically.
/* SORT POST TYPE BY NAME * Using pre_get_posts, sort a post type by name------------------------------------------------------------------------------------------------------- */function xx_sort_post_type_by_name( $query ) { if ( ! is_admin() && $query->get( 'post_type' ) == 'post_type_name' ) { $query->set( 'orderby', 'name' ); $query->set( 'order', 'ASC' ); }}add_filter( 'pre_get_posts', 'xx_sort_post_type_by_name' );
Let’s go through it, step by step. First, we tell WordPress to execute the function xx_sort_post_type_by_name() when the pre_get_posts hook is called. We also pass along a variable called $query into the function. This variable holds the main WordPress $query object, which specifies what content WordPress should query and how.
function xx_sort_post_type_by_name( $query ) { // Code}add_filter( 'pre_get_posts', 'xx_sort_post_type_by_name' );
The pre_get_posts hook is called both on the front-end and the back-end of your WordPress site, which is why we make sure that we’re on the front-end of the site using the is_admin() conditional tag. If we didn’t, the post type would be sorted alphabetically in the admin interface as well. We also check that the query is only for the post type we want to alter, so that other post types – like posts and pages – aren’t unintentionally sorted alphabetically.
if ( ! is_admin() && $query->get( 'post_type' ) == 'post_type_name' ) { // Code}
Finally, we set the $query object to sort post objects by name in ascending order (A-Z).
$query->set( 'orderby', 'name' );$query->set( 'order', 'ASC' );
That’s it! If you’ve followed the steps above correctly, the post type you’ve specified should now be sorted in alphabetical order rather than by publishing date.


