I want add to cart two product at the same time, one is original (current) product and second is from drop-down list
add_action('woocommerce_add_to_cart', 'custome_add_to_cart');
$cnt=2
function custome_add_to_cart() {
global $woocommerce;
$cnt = $cnt + 1;
echo $cnt."X";
echo $p_id=$_POST['assessories'];
$woocommerce->cart->add_to_cart($p_id, 1);
}
Output:-
As you can see in output image below , it adding same drop-down item many time in cart but i want only 1 quantity to add to cart. it seems that add_to_cart function run many times.
What should i do or how to add filter with passing second drop-down product as parameter to add to cart function ? so i can add this product also in cart.
This should work:
Based on following source: https://docs.woothemes.com/document/automatically-add-product-to-cart-on-visit/
The woocommerce “add_to_cart” functions run the hook “woocommerce_add_to_cart”. So, in your code “add_to_cart” is run, which is running “woocommerce_add_to_cart” which runs your code, which runs “add_to_cart”, etcetera etcetera… You created a recursive loop.
You need to find an alternative way, or stop calling
$woocommerce->cart->add_to_cart($p_id, 1);
in your own code.What you might be looking for is a variable product with some attributes!
Anyway if really you want to do that then you just need the remove_action function :
This prevents the action from looping indefinitely and is pretty simple.. So it will be added only once for that product. You might want to get the added to cart quantity and give it as a second parameter to the
WC()->cart->add_to_cart
function so they are both the same quantityThe
__FUNCTION__
is a magic PHP tag just giving you the name of the current fucnction as a string, si if the function name is not the same it will still workThis might be old, but have you tried unsetting the assessories param after adding to cart?, this would break the loop.