【问题标题】:Get all product categories in WooCommerce获取 WooCommerce 中的所有产品类别
【发布时间】:2019-09-03 04:03:31
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

    您需要使用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 …
    )
    

    【讨论】:

    • 不工作。我得到这个 WP_Error 对象([errors] => Array([invalid_taxonomy] => Array ([0] => Invalid taxonomy.))[error_data] => Array ())
    • 抱歉,这段代码已经过测试并且可以工作...... woocommerce 类别的分类法是“product_cat”......所以你在某处搞混了。
    猜你喜欢
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多