简体   繁体   中英

Woocommerce Add To Cart adding whole stock into cart

I am in a condition to add a product with an another product into cart. So that whenever someone is purchasing a product another complementary product should be added to the cart automatically. So here is what i have been trying :

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 the product into session so that i can reset its price to discounted price. But the problem is whenever i try to add a product, the main product got added to the cart perfectly but the complementary one is adding all the available stock into cart and showing the message "You cannot add that amount to the cart — we have 3 in stock and you already have 3 in your cart.".

I am guessing the problem is with the add_to_cart() parameters, i have tried followings :

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

Getting same message with both the lines.

Any suggestions ?

我不确定这会解决您在代码中的问题,但可能是这个插件会做你想做的事情http://woogang.com/product/woocommerce-chained-products-extension/

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