当定义的产品是 WooCommerce 购物车时添加折扣

Add a discount when defined products are WooCommerce cart

我正在尝试为两种产品都在购物车中时设置折扣,无论其他产品是否也在其中。

到目前为止,只需要数组中的两个之一。

add_action( 'woocommerce_cart_calculate_fees', 'discount_for_ab_products' );
function discount_for_ab_products( $cart ) {

$product_ids = array(34,35);

    foreach ($product_ids as $product_id => $product) {

    $product_cart_id = WC()->cart->generate_cart_id( $product );
    $product_ab_in_cart = WC()->cart->find_product_in_cart( $product_cart_id );

    if ( $product_ab_in_cart ) {
        
        $discount = $cart->subtotal * 0.1;

        $cart->add_fee( __( 'Discount', 'woocommerce' ) , -$discount );
        }
    }
}

尝试以下方法,当所有定义的产品 ID 都在购物车中时(在您的情况下是两个),这将提供折扣:

add_action( 'woocommerce_cart_calculate_fees', 'x_products_discount' );
function x_products_discount( $cart ) {
    // Settings below
    $product_ids = array(34, 35); // <== Your defined product Ids
    $percentage  = 10; // <== discount in percentage (10% here)

    $found_ids   = array();
    
    // Loop through cart items
    foreach (WC()->cart->get_cart() as $cart_item ) {
        // Loop through defined product Ids
        foreach( $product_ids as $product_id ) {
            if( in_array( $product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) {
                $found_ids[$product_id] = $product_id;
                break;
            }
        }
    }
    
    // Discount part
    if( count( $found_ids ) === count( $product_ids ) ) {
        $cart->add_fee( __( 'Discount', 'woocommerce' ), -( $cart->subtotal * $percentage / 100 ) );
    }
}

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