如何从 WooCommerce 购物车中获取商品类别?

How do I get items categories from the WooCommerce cart?

我正在编写函数,该函数应检查购物车中是否有具有特定类别的商品。

我的想法是:

add_filter( 'woocommerce_package_rates', 'remove_flat_rate_from_used_products', 10, 2 );

function remove_flat_rate_from_used_products($rates, $package) {
    if( is_woocommerce() && ( is_checkout() || is_cart() ) ) {
        if( check_whether_item_has_the_category() ) {
            unset( $rates['flat_rate'] );
        }
    }

    return $rates;
}

我猜想,get_cart() 函数 returns 购物车的内容,我将能够在那里获得有关商品类别的信息。我需要知道数组get_cart()returns的结构,所以我写了:

function check_whether_item_has_the_category() {
    global $woocommerce;

    var_dump(WC()->cart->get_cart());
}

得到了

Warning: Invalid argument supplied for foreach() in ...wp-content\plugins\woocommerce\includes\class-wc-shipping.php on line 295

然后我尝试在 get_cart() 函数的结果中查找类别名称:

function check_whether_item_has_the_category() {
    global $woocommerce;

    if( in_array('used', WC()->cart->get_cart()) ) {
        echo 'do something';
    }
}

同样的错误。

使用 $woocommerce 而不是 WC() 什么也没做,以及删除 global $woocommerce

我做错了什么以及如何获取项目类别(或检查它们是否存在特定类别)?

变量 $package 还包含购物车内容 ($package['contents']),这是一个包含购物车中所有产品的数组。

所以你可以遍历它,看看单个产品是否有想要的类别。要获取类别,您可以使用 wp_get_post_terms():

function remove_flat_rate_from_used_products($rates, $package) {

    // for each product in cart...
    foreach ($package['contents'] as $product) {
        // get product categories
        $product_cats = wp_get_post_terms( $product['product_id'], 'product_cat', array('fields' => 'names') );
        // if it has category_name unset flat rate
        if( in_array('category_name', $product_cats) ) {
            unset( $rates['flat_rate'] );
            break;
        }
    }

    return $rates;
}