从 Woocommerce 中的优惠券使用中排除具有 2 个特定属性术语的变体

Exclude variations with 2 specific attribute terms from coupon usage in Woocommerce

如果客户的购物车中有任何具有以下属性条款的特定产品变体,我需要阻止使用优惠券:

我查看了适用于限制特定产品和特定类别的 Woocommerce 脚本,但无法弄清楚属性和所有优惠券。

感谢任何帮助。

这可以使用 woocommerce_coupon_is_valid 过滤器挂钩以这种方式完成:

add_filter( 'woocommerce_coupon_is_valid', 'check_if_coupons_are_valid', 10, 3 );
function check_if_coupons_are_valid( $is_valid, $coupon, $discount ){
    // YOUR ATTRIBUTE SETTINGS BELOW:
    $taxonomy   = 'pa_style';
    $term_slugs = array('swirly', 'circle');

    // Loop through cart items and check for backordered items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        foreach( $cart_item['variation'] as $attribute => $term_slug ) {
            if( $attribute === 'attribute_'.$taxonomy && in_array( $term_slug, $term_slugs ) ) {
                $is_valid = false; // attribute found, coupons are not valid
                break; // Stop and exit from the loop
            }
        }
    }
    return $is_valid;
}

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

您还可以检查购物车中的每个产品,并使用 woocommerce_coupon_is_valid_for_product

将其限制在优惠券中
/**
 * exclude a product from an coupon by attribute value
 */
add_filter('woocommerce_coupon_is_valid_for_product', 'exclude_product_from_coupon_by_attribute', 12, 4);
function exclude_product_from_coupon_by_attribute($valid, $product, $coupon, $values ){
    /**
     * attribute Settings
     */
    $taxonomy = 'pa_saison';
    $term_slugs = array('SS22');

    /**
     * check if the product has the attribute and value 
     * and if yes restrict this product from the coupon
     */
    if(in_array($product->get_attribute($taxonomy), $term_slugs)) {
        $valid = false;

    /**
     * otherwise check if its a variation product
     */
    } elseif($product->parent_id) {
        /**
         * set the parent product
         */
        $parent = wc_get_product($product->parent_id);
        
        /**
         * check if parent has an attribute with this value
         */
        if(in_array($parent->get_attribute($taxonomy), $term_slugs)) {
            $valid = false;
        }

    /**
     * for all other products which does not have the attribute with the value
     * set the coupon to valid
     */
    } else {
        $valid = true;
    }

    return $valid;
}

我已经在我的网站上对其进行了测试,它按预期工作。