get_categories() order by “term_order”?

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.

Read More

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);

Related posts

Leave a Reply

4 comments

  1. 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.

  2. 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:

    Unknown column ‘term_order’ in ‘order clause’.

    Because simply, some terms queries are only fetching data from (wp_terms & wp_term_taxonomy) database tables, and do not have any INNER JOIN with (wp_term_relationships) table, which has the term_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:

    function wpcf_filter_terms_order( $orderby, $query_vars, $taxonomies ) {
            return ( ! is_null($query_vars["object_ids"]) ) ? 'term_order' : $orderby;
    }
    
    add_filter( 'get_terms_orderby', 'wpcf_filter_terms_order', 10, 3 );
    
  3. 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.