【问题标题】:How do I get items categories from the WooCommerce cart?如何从 WooCommerce 购物车中获取商品类别?
【发布时间】:2015-07-27 04:25:09
【问题描述】:

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

我的想法是:

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() 函数返回购物车的内容,我将能够获取有关项目类别的信息。我需要知道 get_cart() 返回的数组的结构,所以我写了:

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

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

【问题讨论】:

  • 如果您的购物车中有多个不同类别的产品,是否仍应取消统一费率?
  • 是的,如果该类别至少有一种产品,则应取消统一费率。

标签: php wordpress woocommerce


【解决方案1】:

变量$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;
}

【讨论】:

  • 谢谢,这是一个很好的解决方案。它必须在所描述的情况下完美地工作。我通过反复试验制定了类似的解决方案,花了大约 3 个小时。另外,我尝试在functions.php中使用WooCommerce条件标签时出错。
猜你喜欢
  • 1970-01-01
  • 2018-10-19
  • 2019-01-27
  • 1970-01-01
  • 2021-07-26
  • 1970-01-01
  • 2021-07-22
  • 2019-09-18
  • 1970-01-01
相关资源
最近更新 更多