如果购物车包含两个类别的商品,Woocommerce 会增加费用

Woocommerce add fee if cart contains items from both categories

我有这段代码,我试图检查购物车是否包含来自两个类别的产品; 饮料捆绑包。如果为真,则应用-1的费用。

目前它正在工作,但不太正确,因为它正在检查购物车是否包含 DrinksBundles.

我需要它来检查两个 类别是否都在购物车中,而不仅仅是一个。我确定我缺少的是简单的东西?

add_action( 'woocommerce_cart_calculate_fees','custom_pcat_fee', 20, 1 );
function custom_pcat_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;

// Categories in a coma separated array
$categories = array('drinks','bundles');
$fee_amount = 0;

// Loop through cart items
foreach( $cart->get_cart() as $cart_item ){
    if( has_term( $categories, 'product_cat', $cart_item['product_id']) )
        $fee_amount = -1;
}

// Adding the fee
if ( $fee_amount < 0 ){
    // Last argument is related to enable tax (true or false)
    WC()->cart->add_fee( __( "Kombucha Bundle Discount", "woocommerce" ), $fee_amount, false );
}
}

您可以迭代 $cart->get_cart() 的循环,使用 get_the_terms() 获取类别并推送到数组,然后您可以循环 $must_categories 来检查两个类别是否可用。

add_action( 'woocommerce_cart_calculate_fees','custom_pcat_fee', 20, 1 );
function custom_pcat_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Categories in a coma separated array
    $must_categories = array('drinks','bundles');
    $fee_amount = 0;

    $product_cat = array();

    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item ){
        $terms = get_the_terms( $cart_item['product_id'], 'product_cat' );
        foreach ($terms as $term) {
           $product_cat[] = $term->slug;
        }
    }
    
    array_unique( $product_cat );
    
    foreach ( $must_categories as $key => $must_cat ) {
        
        if( in_array($must_cat, $product_cat) ){
            $fee_amount = -1;
        }else{
            $fee_amount = 0;
            break;
        }

    }

    // Adding the fee
    if ( $fee_amount < 0 ){
        // Last argument is related to enable tax (true or false)
        WC()->cart->add_fee( __( "Kombucha Bundle Discount", "woocommerce" ), $fee_amount, false );
    }
}

已测试并有效