I have a custom taxonomy filled with terms such as ‘volume 1’, ‘volume 2’, ‘issue 1’, ‘issue 2’, ‘issue 10’ and get_terms orderby name returns list as:
issue 1, issue 10, issue 2 though I need it to be issue 1, issue 2, issue 10
I tried searching wp.stackexchange and using my google-fu to no avail. Any help would be greatly appreciated.
I know this post is very old but still answering for others who reach here.
Following is a very simple filter to sort the terms as numbers. You only need to set the variable
$taxonomy_to_sort
withtaxonomy slug
and place it infunctions.php
of your theme.There are many similar posts on the forum, if you look around.
You do not have numbers. Therefore you cannot sort numerically. You have to sort alphabetically and that will give you the pattern you see. I am honestly not even sure if
get_terms
supports a numeric sort (at a glance I’d say it doesn’t) since I doubt many terms are entirely made up of numbers .You have a couple of options.
in pure SQL but it would be tricky– you’d have to
substr
theterm name and sort on that. It would be hairy and probably not very efficient.
before you display them. You’d have to do the same thing as in the
SQL and
substr
the name, sort, and put it back together. Any pagination would be problematic with this approach.Where’s that problems root?
First, you’re asking to sort by a part that is inside some string. This is no native functionality in any programming language.
Second, your actual problem is not “sorting by number”, but the way you constructed those numbers. If you’d have known this issue in front (and taken it into account), you could’ve written a filter that would pad those zeros in front of your numbers.
How to ignore the actual problem and work around it.
This doesn’t really fix the problem, but as we (and maybe you too) don’t know how many “issues” you might come up with (10, 1k, 100k?), we’re just adding the sorting when displaying it. Here’s a template tag for you to use:
I struggled to get this to work,
With a great help from https://objectiv.co/taking-natural-sort-alphanumeric-wordpress-even/