获取WooCommerce中的所有产品类别

时间:2019-04-12 11:37:34

标签: php wordpress woocommerce custom-taxonomy taxonomy-terms

我正在尝试获取WooCommerce中的产品类别,但是get_terms()函数对我不起作用。我得到一个空数组。

我做错了什么?如何获取所有Woocommerce产品类别术语?

1 个答案:

答案 0 :(得分:1)

产品类别是WooCommerce产品使用的“自定义分类法” product_cat

您需要通过{strong>正确的分类法使用get_terms(),方法是:

// 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>';

您还可以使用get_terms()来获得空白的产品类别,例如:

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

经过测试并可以使用(WordPress 3.5+和WooCommerce 2.4+)…两者都应该对您有用。

您将得到类似的东西:

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 …
)
相关问题