Custom sorting Wordpress taxonomy terms 9/8/14

By Chris Johnson

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:

Wordpress term list

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 function3 that we’ll use with PHP’s 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; ?>
  1. A taxonomy term is the generic name for category or tag. Categories and tags are examples of taxonomies.

  2. I rarely use the description field for taxonomy terms, so using it for something else is not a problem.

  3. 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.”