Inevitably, the standard alphabetical sort betrays you. Say you have a list like this:
- Car 1
- Car 2
- Car 3
- Car 4
- … etc
- Car 10
Using an ascending alphabetical sort, you’d end up with this sadness:
- Car 1
- Car 10
- Car 2
- Car 3
- Car 4
- … and so on
If your data is in a PHP array, PHP has a nifty function for this called natsort. It’s only weakness is that it sorts based on the values in the array, not the keys. And if you have an array full of objects, you’re doubly out of luck.
Which is exactly the situation you’ll find yourself in if you need to return a list of WordPress taxonomy terms in a natural, alphanumeric order. To sort those terms naturally, takes a little more effort and a comparison algorithm called strnatcmp.
So here’s a function and an example that do just that:
Doesn’t get much easier than that.