在 Woocommerce 3 中隐藏特定产品类别的购物车优惠券字段

Hide cart coupon field for specific products category in Woocommerce 3

function hidding_coupon_field_on_cart_for_a_category($enabled) {
    // Set your special category name, slug or ID here:
    $special_cat = 'clothing';
    $bool = false;

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $wc_product = $cart_item['data'];
        // Woocommerce compatibility
        $product_id = method_exists( $wc_product, 'get_id' ) ? $wc_product->get_id() : $wc_product->id;
        if ( has_term( $special_cat, 'product_cat', $product_id ) )
            $bool = true;
    }

    if ( $bool && is_cart() ) {
        $enabled = false;
    }
    return $enabled;
}
add_filter( 'woocommerce_coupons_enabled', 'hidding_coupon_field_on_cart_for_a_category' );

找到了这个片段并且效果很好,但是如果我有一个变量而不是一个简单的产品,类别隐藏似乎不再起作用。

$special_cat = 'prints';
$product_id  = array('9461', '9597');

同样排除主要产品 ID 和变体 ID 也不起作用。有人有想法吗?

Update 2 - October 2018 (still perfectly work on last Woocommerce version)

要使其适用于所有产品类型包括可变产品,请改为使用:

add_filter( 'woocommerce_coupons_enabled', 'product_category_hide_cart_coupon_field', 20, 1 );
function product_category_hide_cart_coupon_field( $enabled ) {
    // Only on frontend
    if( is_admin() ) 
       return $enabled;

    // Set your special categories names, slugs or IDs here in the array:
    $categories = array('prints');
    $found = false; // Initializing

    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ){
            $found = true;
            break; // We stop the loop
        }
    }

    if ( $found && is_cart() ) {
        $enabled = false;
    }
    return $enabled;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。