I’d argue that, at this point in time, working with WordPress taxonomies has never been easier.

Sure, creating, tagging or categorized, and adding custom taxonomies to posts and custom post types has always been relatively easy, but when it comes to implementing a solution that utilizes custom post types and/or custom taxonomies, then constructing queries can sometimes be a bit of a pain.

But now, we have more API functions and features than ever before:

Of course, there are still cases in which retrieving and organizing data still leaves something to be desired. 

I don’t fault WordPress for this, though. It’s more of a function of how data is ordered within databases, applications, and in computers in general.

WordPress Terms in Alphabetical Order

Specifically, one example is trying to order terms in alphabetical order then the actual terms are named something like this:

  • Acme 1
  • Acme 2
  • Acme 9
  • Acme 10
  • Acme 11

For anyone who has dealt with data like this in the past, you know that when you query the information and you ask to order it ascending order, you’re going to get it back like this:

  • Acme 1
  • Acme 10
  • Acme 11
  • Acme 2
  • …and so on.

Sure, there are plenty of algorithms that are available in order to sort the information in alphabetical order, but PHP does have a built in function that makes this trivially easy given an array of information.

A Concrete Example

Usually, I find that seeing this material in the context of a concrete example helps to make it a bit more clear. To that end, let’s say that we have a book composed of chapters.

To that end, we’ll have a taxonomy called `book` and its children will be `chapters`.  Then, the steps will be as follows:

  1. Query for the term by the taxonomy.
  2. Setup an associative array.
  3. Order the terms.

Sounds easy enough, right? Assuming that you’re comfortable working with `get_term_by`, `array_push`, and `natsort`, it is.

Take a look at the following gist:

The comments should provide enough information for exactly how this works. Note that I’m also aware there are improvements that can be made, but for the sake of making the example as clear as possible, I’ve opted to share it as is.

I’d rather people understand the point of what I’m trying to share rather than demonstrate how compact code can be.

But This Isn’t The Only Option

Here’s the thing: this strategy works well if you have a relatively small data set and if you’re okay with using the term IDs and term names to help organize your information.

I’m not making the case that this is the best way to do this, or that it’s the primary option as it relates to ordering data – there are always alternatives and they are unique to your situation.

However, if you’re looking for a quick way to naturally place taxonomy terms in alphabetical order, have a relatively small data set, and don’t mind working with an associative array, then the above solution is one that works well.