Ordering WordPress taxonomies

I came across an issue the other day when I was working on The Band Company website that required me to order a taxonomy numerically.  The issue was, that even though the items that I was ordering were numbers, they were being ordered alphabetically.  This is what I did to solve the issue.

The site lists bands that you can hire for your event, and each of these bands has a custom taxonomy associated with them that lists the price range they are in.  These price ranges are 500 or less, 501-800, 801-1000, 1001-1500, and 1501+.  On the search page the brief was to display these ranges in ascending alphabetical order.

To get the taxonomy and order you would use the following

$price_ranges = get_terms('price-range', array(
  'orderby' => 'name',
  'order' => 'ASC',
));

You can view the full documentation for get_terms on the WordPress Codex.

As said earlier – this returned them in alphabetical order, so 1001-1501 was appearing before 501-800.  Enter the world of usort.  Usort allows you to order an array by providing a function that does the ordering.

get_terms will return an array of taxonomy objects,  we will need to bear that in mind in our callback function.  Here is the one that I came up with.

function my_taxonomy_sort($a, $b) {
  $name_a = explode("-", $a->name);
  $name_b = explode("-", $b->name);

  if($name_a[0] == $name_b[0]) {
    return 0;
  }
  return ($name_a[0] < $name_b[0]) ? -1 : 1;
}

In the function I am interested in ordering based upon the name, and as the name is in the format [low value][high value] I explode it into an array for easy access.  I can then compare the first part (the only bit that I am interested in) and return the relevant response to usort.

It is now as simple as doing the following to get the taxonomies in the order that I want.

$price_ranges = get_terms('price-range');
usort($price_ranges, 'my_taxonomy_sort');

$price_ranges is now in the order that I want to output in.

I know it is not as nice as having the db sort the fields on select, but it works. Hope this helps someone out there.


Posted

in

by

Comments

Leave a Reply