Martin
Martin

Reputation: 795

Woocommerce order categories by category order as per admin section

In the woocommerce categories screen you can drag and drop the categories to change their order.

In the "front end" I want to list the categories in this same order (same custom order as per the drag and drop of Product Categories screen in wp-admin).

$args = array(
  'taxonomy'     => 'product_cat',
  'orderby'      => 'term_order',
  'order'        => 'asc',
  'show_count'   => 0,
  'pad_counts'   => 0,
  'hierarchical' => 1,
  'title_li'     => '',
  'hide_empty'   => 0,
);

$query = new WP_Query( $args );

I have tried several different orderby variations but can't get the exact same order as per the admin screens. The ordering data seems to be stored in the ??__woocommerce_termmeta table with 'meta_key' of 'order'.

Any suggestions would be greatly appreciated.

Thanks.

Upvotes: 2

Views: 3858

Answers (1)

Danijel
Danijel

Reputation: 12689

It seems that WooCommerce is already changing the query in the case of product_cat taxonomy. For example:

$args = array(
    'parent'        => 0,
    'taxonomy'      => 'product_cat'
);

$categories = get_categories( $args );

Executed query will look like this:

SELECT t., tt., tm.* FROM wp_terms AS t INNER JOIN wp_term_taxonomy AS tt ON t.term_id = tt.term_id LEFT JOIN wp_woocommerce_termmeta AS tm ON (t.term_id = tm.woocommerce_term_id AND tm.meta_key = 'order') WHERE tt.taxonomy IN ('product_cat') AND tt.parent = '0' ORDER BY tm.meta_value+0 ASC, t.name ASC

And categories are taken in the same order as in the admin section.

Upvotes: 5

Related Questions