Custom sorting Wordpress taxonomy terms 9/8/14
Using Wordpress’s get_terms
function, you can retrieve an array of taxonomy terms
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:
<?php $terms = get_terms( 'my_custom_taxonomy' ); ?>
Next, we need to define a comparison function
usort
to compare the numerical values of the description fields:
<?php
function description_compare( $a, $b ) {
return $a->description - $b->description;
}
?>
Finally, we can sort our array using usort
with our comparison function:
<?php usort($resource_terms, "description_compare"); ?>
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:
<?php foreach( $terms as $term ): ?>
<a href="<?php get_term_link( $term ) ?>"><?php echo $term->name ?></a>
<?php endforeach; ?>
-
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.” ↩