This week I had an interesting challenge. To order all posts within a website alphabetically for a college course directory. Additionally, the News & Events category would need to remain organized by newest to oldest.
Besides being used to create an alphabetized list of posts this can be useful for posting a series of posts in numerical order.
Admittedly, the easiest solution would have been to use a plugin like Category Order and Taxonomy Terms Order which can easily be configured to do the task.
However, I prefer to write my own code whenever practical and WordPress offers the the is_category() conditional tag allowing me to add a little custom code to my child theme’s functions.php file.
Referencing the code below, the following overrides take place.
- pre_get_posts provides a hook to change how $query runs the loop
- I give my function an unique name of ims_change_sort_order which will serve as a reminder of what it does. In this case change the sort order of the Intercollegiate Media Studies website
- the if statement looks for the string ‘news-events’ slug and in the following lines set the $query order to ‘DESC’ descending followed by an orderby post_date
- elseif will then tell WordPress to order all other post categories that are not ‘news-events’ by ‘ASC’ ascending order and orderby title. This is accomplished by using the exclamation point NOT logical operator
<?php
/*
* Order news-events by descending order
* All other archives are ordered by title alphabetically
*/
add_action( 'pre_get_posts', 'ims_change_sort_order');
function ims_change_sort_order($query){
if(is_category('news-events')) {
// Set the order to DESC descending
$query->set( 'order', 'DESC' );
// Set the orderby date so it loops newest to oldest posts
$query->set( 'orderby', 'post_date' );
}
elseif( !is_category( 'news-events' )) {
//Set the order ASC ascending
$query->set( 'order', 'ASC' );
//Set the orderby title so it loops A-Z
$query->set( 'orderby', 'title' );
}
};
?>
I then added the code above to my WCLAX Child Theme for local testing. Once satisfied everything worked as expected I added it to the actual website’s child theme.
You can download my modified WCLAX Child Theme if you’d like to see how the code works.
Note: All posts will be ordered alphabetically except a category slugged news-events which will order by post date most recent.
I should point out adding custom functionality to your Child Theme is not always the best solution. For instance, if you switch themes in the future you’ll need to add this code to the new Child Theme or migrate the code to a custom plugin so it can be enabled as needed.
Leave a Reply