简体   繁体   中英

Add a discount when defined products are WooCommerce cart

I am trying to set a discount for when BOTH products are in the cart no matter what other products are also in there.

As of now, all it takes is one of the two within the array.

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 );
        }
    }
}

Try the following instead, that will make a discount when all defined product ids are in cart (so two in your case):

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 ) );
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM