Ordering post by taxnomy


The wordpress post query functions have many excellent features built in for selecting and ordering a post query, but the one thing it can’t do is order by taxonomy name. For the average user, this is not a big deal, but once you start making complicated relationships with custom post types and taxonomies, it can be critical. Fortunately I stumbled upon this little function that allows sorting by a custom taxonomy name. Unfortunately it didn’t play well with anything but the simplest queries and was limited to only one taxonomy. I made a few adjustments to the function to allow sorting by any taxonomy.

Notice that I have defined the sortable taxonomies in an array. If you wanted to be able to sort by anything without having to first define it in this array, you could use the is_tax() function. This function will run every single time posts are queried, so I would caution against using is_tax() as it could potentially slow your site down. While it would be much simpler to eliminate the $taxonomies array and use is_tax($wp_query->query[‘orderby’]) instead of in_array($wp-query->query[‘orderby’], $taxonomies), I opted for speed over ease of use.

To enable taxonomy term sorting, copy the script into your functions.php file and replace the $taxonomies array with an array of your taxonomy slugs. Then in you post query simply set the orderby parameter to the taxonomy slug you want to sort by.