仅当购物车商品来自 3 个不同的产品类别时才自动添加优惠券折扣

Auto add a coupon discount only when cart items are from 3 different product categories

在 WooCommerce 中,我想通过 WooCommerce 优惠券功能 增加 10% 的折扣,仅当客户购买来自 3 个不同产品类别的产品时 (如类别 1,类别 2, 类别 3).

如何使用 WooCommerce 优惠券功能完成此操作?

如有任何帮助,我们将不胜感激。

更新说明: 我只有 3 个父产品类别,没有子类别。每个产品都分配给一个类别。有些产品是可变的,有些是简单的。

这是一个不使用优惠券代码的解决方案,我从之前的 question 中回收了优惠券代码。

add_action( 'woocommerce_cart_calculate_fees' , 'add_multiple_category_discount' );

function add_multiple_category_discount( $cart ){
    if( $cart->cart_contents_count < 3 ){
        return;
    }

    $product_cats = array();

    foreach( $cart->get_cart() as $item ) {
        $product = wc_get_product( $item['product_id'] );

        foreach( $product->get_category_ids() as $key => $cat_id ) {
            if( ! in_array( $cat_id, $product_cats ) )
                $product_cats[] = $cat_id;
        }
    }

    // If we have 3 distinct categories then apply a discount
    if( count( $product_cats ) >= 3 ) {
        // Add a 10% discount
        $discount = $cart->subtotal * 0.1;
        $cart->add_fee( 'You have 3 different product categories in your cart, a 10% discount has been added.', -$discount );
    }
}

To handle this functionality with a coupon you will need to have one product category by product or one parent category by product, because a product can have many categories and subcategories set for it.

当购物车商品来自 3 个不同的产品类别时,此自定义功能将添加优惠券折扣。如果从购物车中删除购物车商品并且不再有 3 个不同的产品类别,优惠券代码将被自动删除。

您还需要在函数中设置优惠券代码名称和所有匹配产品类别 ID 的数组。

代码如下:

add_action( 'woocommerce_before_calculate_totals', 'add_discount_for_3_diff_cats', 10, 1 );
function add_discount_for_3_diff_cats( $wc_cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // HERE set your coupon code and your parent product categories in the array
    $coupon_code_to_apply = 'summer';
    // HERE define your product categories IDs in the array
    $your_categories = array( 11, 13, 14 ); // IDs

    // If coupon is already set
    if( $wc_cart->has_discount( $coupon_code_to_apply ) )
        $has_coupon = true;

    foreach( $wc_cart->get_cart() as $cart_item ) {
        $product_id = $cart_item['product_id'];
        $product = wc_get_product($product_id);
        foreach( $product->get_category_ids() as $category_id ) {
            if( has_term( $your_categories, 'product_cat', $product_id ) && in_array( $category_id, $your_categories ) ){
                // Set the categories in an array (avoiding duplicates)
                $categories[$category_id] = $category_id;
            }
        }
    }

    $count_cats = count($categories);
    $has_discount = $wc_cart->has_discount( $coupon_code_to_apply );

    if ( 3 <= $count_cats && ! $has_discount ) {
        $wc_cart->add_discount($coupon_code_to_apply);
    } elseif ( 3 > $count_cats && $has_discount ) {
        $wc_cart->remove_coupon($coupon_code_to_apply);
    }
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

经过测试并适用于简单且可变的产品……