According to the WordPress codex, the get_categories() method accepts the following arguments for its orderby property:
**orderby** (string) Sort categories alphabetically or by unique category ID. The default is sort by Category ID. Valid values:
id
name - default
slug
count
term_group
However, taking a look into the “wp_term_relationships” table there is a seemingly unused field called “term_order” which, for every category I’ve ever created is set to 0.
Is it possible to use the term_order field in order to serve as an indexed sort order for categories?
I’ve placed incremental values into this field for my categories and I’m trying to pass the order to the function with the code below to no avail:
$cat_args=array(
'hierarchical' => 0,
'orderby' => 'term_order',
);
$categories = get_categories($cat_args);
Many years later,
You can add this code in your functions.php :
This code force WP to use the orderby => term_order argument in your term query.
The answer by @cédric-dagherir-dahive which suggests using
get_terms_orderby
filter is a great approach to display terms in the order they were added to the object (post). However, it does not work for all terms queries, and would generate the following error:Because simply, some terms queries are only fetching data from (
wp_terms
&wp_term_taxonomy
) database tables, and do not have anyINNER JOIN
with (wp_term_relationships
) table, which has theterm_order
field. Hence the error message.The
order by term_order
clause should only be added if the query is concerned about the many-to-many relationship between the taxonomy and the object (e.g.get_the_terms
).Therefore, I updated the code to firstly check if the term query involves objects before adding the
term_order
to the order clause:I’ve searched all the wordpress functions and the only one you can use with
'term_order'
is wp_get_object_terms and you can see its function here.From this point on, even if wordpress doesn’t use this to filter the categories in
get_categories()
you or other theme/plugin developers can use the above function to get object_terms and to order/filter them by term_order.A few more years later I found this solution:
The task can be solved with a filter and an adapted taxonomy.
https://core.trac.wordpress.org/ticket/5857#comment:4