Custom sorting Wordpress taxonomy terms 9/8/14
Using Wordpress’s get_terms
function, you can retrieve an array of taxonomy terms1 sorted by name (the default), id, count, or slug. If you need more control, you can hijack the term description field2 and use it for sorting.
The first step is populating our term description fields with values we can use for sorting. Numbers are the easy choice and in this example, lower numbers will be sorted ahead of higher numbers:
In our theme we’ll need to pull in the array of terms with get_terms
. Be sure to replace my_custom_taxonomy
with your taxonomy name:
Next, we need to define a comparison function3 that we’ll use with PHP’s usort
to compare the numerical values of the description fields:
Finally, we can sort our array using usort
with our comparison function:
Now, when you loop through the $terms
array, it should be in the order you defined in your description fields. Here’s an example of how you could output the terms:
-
A taxonomy term is the generic name for category or tag. Categories and tags are examples of taxonomies. ↩
-
I rarely use the description field for taxonomy terms, so using it for something else is not a problem. ↩
-
From the PHP documentation: “The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.” ↩