Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress get_categories() order by "term_order"?

Tags:

php

wordpress

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);
like image 674
jcoder Avatar asked Oct 21 '22 15:10

jcoder


1 Answers

Many years later,

You can add this code in your functions.php :

function wpcf_filter_terms_order( $orderby, $query_vars, $taxonomies ) {
    return $query_vars['orderby'] == 'term_order' ? 'term_order' : $orderby;
}

add_filter( 'get_terms_orderby', 'wpcf_filter_terms_order', 10, 3 );

This code force WP to use the orderby => term_order argument in your term query.

like image 187
Cédric Dagherir - DaHive Avatar answered Oct 25 '22 20:10

Cédric Dagherir - DaHive