I am populating an unordered list by the results from get_terms() assigned to a variable. What I would like to do is order the results in a specific order in the unordered list. How would I do this? I looked into using the orderby argument for the get_terms() function but none of the parameters for that seem to work the way I need them to. How do I define a specific order for them to be displayed in? So basically my unordered list looks like this once populated:
- Atletics
- Community
- Corporate
- Healthcare
- Higher Education
- k-12
And I want it to look like this:
- k-12
- higher education
- healthcare
- atletics
- Corporate
- community
The best option is to write a wrapper function for
get_terms
and then useusort()
to sort the terms in the order you want.Here is the code, I have commented the code to make it easy to follow and to understand (NOTE: This code requires PHP 5.4+)
There are four parameters to the function
$taxonomy
This is the taxonomy from which to get terms from. Default: empty string$args
This is all the valid arguments that can be passed toget_terms
. You can check outget_terms
for valid arguments. Default: empty array$term_order
The slugs or names or ids of the terms in the specific order you want them sorted. This can be an array of slugs/names/ids or a comma separated string of slugs/names/ids. Default empty stringExamples
This will display the terms in order of
term-3, term-1, term-2
$sort_by
By which field the terms must be sorted. The default value is slugs, so this means that you should pass a string or an array of terms slugs to the$term_order
parameter. If you need to pass term names to the$term_order
parameter, then you need to set the value of$sort_by
toname
. You can also pass, if you wish, term ids to$term_order
, in which case you then need to set the$sort_by
value toterm_id
USAGE
In your template, you will use the function as follow with the following example
Taxonomy name is
category
, we don’t want to set any specific argument, we need sort the terms by name in the following orderTerm C, Term A, Term B
You will then do the following: (
$term_order
as an array)(
$term_order
as a string)One problem I’ve found with setting an order that the client wants, is that the client will later want to re-order the list so another way to allow a desired order and ability to alter that later without adjusting the code would be the following:
get_terms()
function and include the following settings in the array. In this examplejht_order
is the name of the custom field.Now the terms will be ordered by the value of this field. Note: if the term doesn’t have this field populated, it won’t be returned by
get_terms()
Update: If the custom field is a number, you’ll want to change ‘orderby’ to be ‘meta_value_num’ so it will sort it as a number and not as ascii.