Yesterday I gave an example of how to filter the result from get_terms in WordPress to use a natural order, rather than alphanumeric.
So, this:
- Car 1
- Car 2
- …
- Car 10
Not this:
- Car 1
- Car 10
- Car 2
- … and so on
Today, I’m going to show you how to add a new orderby parameter to get_terms that will do the hard work for you, as well as show you how to handle situations where you do not normally have control over the sort order, such as the WordPress Admin area.
In order to add a new orderby parameter to get_terms for natural sort, we simply need to use the get_terms filter, which gives us not only access to the list of terms, but also the arguments that were passed in. So with a small amount of effort, we can extend get_terms to do what we want:
Now, what about the admin area? Say you want to change the order of terms in the post editor. We can do that as well with one more filter, and a bit of hackish code to figure out where we are.
Here are my assumptions:
- You only want to sort categories, not tags or custom taxonomies.
- You want to do this on the new post page, as well as the edit post screen.
- You want to do this regardless of post type.
These things being true, here would be the way to accomplish this. This code assumes you have already implemented the filter above!
That should be all there is to it. Let me know if you have any problems with the above code snippets.
ordinarycoder says
Thanks man!
Greg Olynyk says
I have a couple plugins that sort posts by Title alphanumerically, where chapters list;
1 – First Chapter
10 – Tenth chapter…
2 – second chapter…
3 – third…
where to adjust these plugins to sort by Post title or Filename “Natural” sort order ?
1. file-away
2. Posts Table with Search & Sort