wp_list_categories: order by term order?

I am currently using WordPress’ wp_list_categories function in order to retrieve my terms from a specified taxonomy. I like this function for its ability to generate (hierarchical) HTML lists, that are equipped with proper class names, etc.

I have sorted my terms using the Simple Custom Post Order plugin, which works fine when I’m listing all terms the regular way (i.e. using get_terms).

However, whenever I try to list my terms using wp_list_categories, somehow it does not accept the “orderby” argument when using “term_order” (or “menu_order”).

Could somebody point me in the right direction here?

I’ve provided my code below:

$categories = wp_list_categories([
     'taxonomy' => 'news_category',
     'title_li' => '',
     'orderby' => 'menu_order',
     'order' => 'ASC',
     'echo' => 0,
     'current_category' => $current_term_id,
     'depth' => 0
]);

Edit: I used menu_order, while I should have been using term_order. Still, I hope this serves somebody, some day 🙂

1 Answer
1

The wp_list_categories() function calls the get_categories() function, that’s a wrapper for the get_terms() function, that creates an instance of the WP_Term_Query class. It doesn’t look like it supports ordering by term order.

If the plugin uses the term_order column in the wp_terms table, then you can try to add a support for it’s ordering, via the get_terms_orderby filter:

add_filter( 'get_terms_orderby', function( $orderby, $qv, $taxonomy )
{
    // Only target the category taxonomy
    if( 'category' !== $taxonomy )
        return $orderby;

    // Support orderby term_order
    if( isset( $qv['orderby'] ) && 'term_order' === $qv['orderby'] )
        $orderby = 't.term_order';

    return $orderby;
}, 10, 3 );

where we only support this for the category taxonomy.

Another approach is to add the filter and remove it right after your wp_list_categories() call.

Leave a Comment