How to add filter or hook for "woocommerce_add_to_cart"
This should work:
add_action('woocommerce_add_to_cart', 'custome_add_to_cart');function custome_add_to_cart() { global $woocommerce; $product_id = $_POST['assessories']; $found = false; //check if product already in cart if ( sizeof( WC()->cart->get_cart() ) > 0 ) { foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) { $_product = $values['data']; if ( $_product->id == $product_id ) $found = true; } // if product not found, add it if ( ! $found ) WC()->cart->add_to_cart( $product_id ); } else { // if no products in cart, add it WC()->cart->add_to_cart( $product_id ); }}
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 :
add_action('woocommerce_add_to_cart', 'custome_add_to_cart');function custome_add_to_cart() { $p_id=$_POST['assessories']; remove_action('woocommerce_add_to_cart', __FUNCTION__); WC()->cart->add_to_cart( $p_id );}
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 quantity
The __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 work