Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all product categories in WooCommerce

I am trying to get product categories in WooCommerce, but get_terms() function doesn't work for me. I am getting an empty array.

What I am doing wrong? How to get all Woocommerce product category terms?

like image 727
abdul wadood Avatar asked Apr 12 '19 11:04

abdul wadood


People also ask

How do I show all product categories in WooCommerce?

Go to WooCommerce > Settings, select the Products tab, and then choose the Display option. For each of the Shop Page Display and Default Category Display options, select Show both. Click the Save changes button to save.

How do I display WooCommerce products by subcategory?

Click on Appearance > Customize. Then go to WooCommerce > Product Catalog. Select “show subcategories” from Category Display. Click on Save Changes.


1 Answers

Product category is a "custom taxonomy" product_cat used by WooCommerce products.

You need to use get_terms(), with the correct taxonomy, this way:

// Get Woocommerce product categories WP_Term objects
$categories = get_terms( ['taxonomy' => 'product_cat'] );

// Getting a visual raw output
echo '<pre>'; print_r( $categories ); echo '</pre>';

You can also get empty product categories using get_terms() like:

$categories = get_terms( ['taxonomy' => 'product_cat', 'hide_empty' => false] );

Tested and works (WordPress 3.5+ and WooCommerce 2.4+)… Both should works for you.

You will get something like:

Array
(
    [0] => WP_Term Object
        (
            [term_id] => 83
            [name] => Uncategorized
            [slug] => uncategorized
            [term_group] => 0
            [term_taxonomy_id] => 83
            [taxonomy] => product_cat
            [description] => 
            [parent] => 0
            [count] => 5
            [filter] => raw
            [meta_value] => 1
        )

    [2] => WP_Term Object
        (
            [term_id] => 11
            [name] => Tshirts
            [slug] => tshirts
            [term_group] => 0
            [term_taxonomy_id] => 11
            [taxonomy] => product_cat
            [description] => 
            [parent] => 0
            [count] => 13
            [filter] => raw
            [meta_value] => 2
        )
    // … and so on …
)
like image 164
LoicTheAztec Avatar answered Oct 19 '22 21:10

LoicTheAztec