Search code examples
phpwordpresswoocommercecustom-taxonomytaxonomy-terms

get_terms ignores orderby argument on WooCommerce product categories


I used the following function for listing product categories and order them by name. Since I last updated WooCommerce from 3.5.7 to 3.6.1 and this is not working any more.

It does not matter, what I write into orderby. The terms are ordered by id I guess, in the same order as in the backend.

I had this problem before, but then I added 'menu_order' => false and it worked. But since the update nothing works any more.

$terms = get_terms( 'product_cat', array(
       'orderby'           => 'name', 
       'order'             => 'ASC',
       'parent' => 2063,
       'menu_order' => false,
       'suppress_filter' => false
   ) );

I Also tried to switch themes without success. Any help is welcome.

I use WordPress version 5.1.1 and Storefront theme version 2.4.5.


Solution

  • Update 2 - Solved

    After I reported this issue on Github WooCommerce, it was clearly a bug affecting orderby argument when calling get_terms() function. It's now approved and patched.

    The issue is solved on Woocommerce update 3.6.2


    First since WordPress 4.5 taxonomies should be passed via the ‘taxonomy’ argument in the argument array on get_terms() function.

    You can not use 'menu_order' and 'suppress_filter' arguments, as they are not defined for WP_Term_Query Class. Instead of 'menu_order', you will use 'orderby' => 'order',.


    Now the allowed arguments for WordPress get_terms() function are listed in WP_Term_Query __construct().

    So YES you can use "orderby" argument:

    • The defaults value is set to name.
    • Accepts term fields (name, slug, term_group, term_id, id, description, parent), count for term taxonomy count, include to match the order of the $include param, slug__in to match the order of the $slug param, meta_value, meta_value_num, the value of $meta_key , the array keys of $meta_query, or none to omit the ORDER BY clause.

    So your code should be something like:

    $terms = get_terms( array(
        'taxonomy' => 'product_cat',
        // 'orderby'  => 'name', // <=== Default orderby is already 'name'
        'order'    => 'ASC',
        'parent'   => 2063,
    ) );
    

    Tested and