【问题标题】:Exclude products with specific attributes terms from WooCommerce coupons从 WooCommerce 优惠券中排除具有特定属性条款的产品
【发布时间】:2021-04-13 11:20:21
【问题描述】:

我想从所有 WooCommerce 优惠券中排除具有特定属性(例如 attribute_pa_brand => mybrand)的产品。

我遵循了这个答案Exclude variations with 2 specific attribute terms from coupon usage in Woocommerce,但它似乎只适用于 Variable Product 类型,而我只需要它用于 Simple Product

如果有任何答案,我将不胜感激。

【问题讨论】:

    标签: php wordpress woocommerce coupon taxonomy-terms


    【解决方案1】:

    linked code from your question 用于产品变体类型。现在要使其适用于简单产品和可变产品(不针对特定的变体属性术语),您将使用以下内容:

    add_filter( 'woocommerce_coupon_is_valid', 'custom_coupon_validity', 10, 3 );
    function custom_coupon_validity( $is_valid, $coupon, $discount ){
        // YOUR ATTRIBUTE SETTINGS BELOW:
        $taxonomy   = 'pa_brand'; // Set the taxonomy (start always with "pa_" + the slug)
        $term_names = array('Apple', 'Sony'); // Set your term NAMES to be excluded
    
        $term_ids = array(); // Initializing
    
        // Convert term names to term Ids
        foreach ( $term_names as $term_name ) {
            // Set each term id in the array
            $term_ids[] = get_term_by( 'name', $term_name, $taxonomy )->term_id;
        }
    
        // Loop through cart items and check for backordered items
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            $product = $cart_item['variation_id'] > 0 ? wc_get_product($cart_item['product_id']) : $cart_item['data'];
            // Loop through product attributes
            foreach( $product->get_attributes() as $attribute => $values ) {
                if( $attribute === $taxonomy && array_intersect( $values->get_options(), $term_ids ) ) {
                    $is_valid = false; // attribute found, coupons are not valid
                    break; // Stop and exit from the loop
                }
            }
        }
        return $is_valid;
    }
    

    代码进入活动子主题(或活动主题)的functions.php 文件中。在上一个 WooCommerce 版本上测试并适用于简单和可变的产品。

    【讨论】:

    • 谢谢洛伊克。我非常希望你的回答。它完美地工作。希望能再次见到你!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 2021-12-30
    • 2017-06-06
    相关资源
    最近更新 更多