Woocommerce Add to Cart Add All to Cart

I am able to add a product with another product to the cart. So every time someone buys a product, another additional product is automatically added to the basket. So here is what I tried:

function save_gift_wrap_fee( $cart_item_key ) {

    if( $_POST['offered-product-id'] )
    {
        global $woocommerce; 
        if($_POST['offered-product-variation-id']){
           $woocommerce->cart->add_to_cart($_POST['offered-product-id'],'1',$_POST['offered-product-variation-id'],array('Flavour'=>$_POST['offered-product-variation-name']),null);    

        }
        else{
            $woocommerce->cart->add_to_cart($_POST['offered-product-id'],'1');       

        }

        WC()->session->set( $cart_item_key.'_offered_product_id', $_POST['offered-product-id'] );
        WC()->session->set( $cart_item_key.'_offered_product_price', $_POST['offered-product-price'] );
        WC()->session->set( $cart_item_key.'_offered_variation_id', $_POST['offered-product-variation-id'] );
    }
    else
    {
        WC()->session->__unset( $cart_item_key.'_offered_product_id' );
    }   

}
add_action( 'woocommerce_add_to_cart', 'save_gift_wrap_fee', 1, 5 ); 

I am adding a product to the session so that I can reset its price at a reduced price. But the problem is that when I try to add a product, the main product is added to the basket, but the additional one adds all the available stocks to the basket and displays the message "You cannot add this amount to the basket - we have 3 in stock, and you have already have 3 in your cart. "

I assume the problem is with add_to_cart () parameters, I tried the following:

$woocommerce->cart->add_to_cart($_POST['offered-product-id'],'1',$_POST['offered-product-variation-id'],array('Flavour'=>$_POST['offered-product-variation-name']),null);

and

$woocommerce->cart->add_to_cart($_POST['offered-product-id'],1,$_POST['offered-product-variation-id'],array('Flavour'=>$_POST['offered-product-variation-name']),null);

Receiving the same message with two lines.

Any suggestions?

+4

Source: https://habr.com/ru/post/1598806/


All Articles