ncesar
ncesar

Reputation: 1792

Get an array of product categories term names order by "menu order" in Woocommerce

I have the following code that searches WooCommerce categories and throws them in custom tabs:

function wcbox_get_woo_categories()
{
    $wp_cat = get_categories(array('hide_empty' => 0, 'taxonomy' => 'product_cat' ));

    $result = array();
    foreach ($wp_cat as $cat)
    {
        $result[] = array('value' => $cat->name, 'label' => $cat->name);
    }
    return $result;
}

It works perfectly, the problem is that instead of putting the categories in order one by one, it puts in alphabetical order.

The whole problem has its origin when I put months into the categories and I look for them with this function. The categories should follow the order of the months, but because of this function, they follow in alphabetical order.

How I can fix this problem?

for further infos, I'm using the WCBox plugin.

This is how its working right now: enter image description here

It shows categories and the product.

The plugin also has this array

            array(
                'type' => 'multiselect',
                'name' => 'filter_category',
                'label' => __('Choose Categories', 'wcbox'),

                'items' => array(
                    'data' => array(
                        array(
                            'source' => 'function',
                            'value'  => 'wcbox_get_woo_categories',
                        ),
                    ),
                ),
                'dependency' => array(
                    'field'    => 'filter_type',
                    'function' => 'vp_dep_is_categories',
                ),
            ),  

Upvotes: 2

Views: 1579

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253814

That is very strange as by default product categories orderby is set by menu order. So maybe something else is interfering in this process.

In backend (settings) Products > categories, each term need to be ordered as you want them to be displayed (by menu order).

You can use directly get_terms() WP function instead of get_categories() (that uses get_terms()).

To force the menu order in your case, use the following:

function wcbox_get_woo_categories() {

    $term_names = get_terms( array(
        'hide_empty' => 0, 
        'taxonomy'   => 'product_cat', 
        'orderby'    => 'meta_value_num', 
        'meta_key'   => 'order',
        'fields'     => 'names',
    ) );

    $result = array();

    foreach( $term_names as $term_name ){
        $result[] = array( 'value' => $term_name, 'label' => $term_name );
    }

    return $result;
}

It should works.

Upvotes: 1

Related Questions