6

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 ?

1 Answers1

0

Im not sure that this will solve your problem in the code, but could be this plugin will do what you trying to do http://woogang.com/product/woocommerce-chained-products-extension/

BenB
  • 2,747
  • 3
  • 29
  • 54
  • thanks , but i am done with all the custom code just the qunatity thing left. Do you know what am i doing in the code wrong ? – Diksha Bhatt Jul 21 '15 at 04:58