Normally it sounds like a pretty simple task. I want to add a (gift) product to the cart, when a specific product is added to the cart. As soon as the "normal product" is removed, the free product should be removed as well.
My current approach is to add the free product to the cart with custom meta data. If the remove button will be clicked, it will check for the meta and only remove these ones.
My problem is that the free product is only added to the cart once. If I remove this "check" the function doesn't work anymore. What am I doing wrong?
/* Add Free Gift for Products */
function gift_add_product_to_cart() {
$product_id = array(20070, 39039); // Product Id of the free product which will get added to cart
$allowedprdIds = array(38162, 38157); // Product Ids of the products where the free product will be added
$is_present = false;
$is_allowedPrd = false;
$cart = WC()->cart->get_cart();
//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 (in_array($_product->get_id(), $product_id)){
$is_present = true;
}
if (in_array($_product->get_id(), $allowedprdIds) ){
$is_allowedPrd = true;
}
}
// if free product not found, add it
if (!$is_present && $is_allowedPrd){
foreach($product_id as $freeProduct => $id){
/*WC()->cart->add_to_cart(20070);*/
WC()->cart->add_to_cart($id,1, NULL, NULL, array('freeDosMas' => 'yes'));
}
}
}
}
add_action( 'woocommerce_add_to_cart', 'gift_add_product_to_cart', 10, 2 );
/* Remove Free Product if Produkt removed */
function remove_gift_from_cart() {
global $woocommerce;
$prod_to_remove = array(20070, 39039); // Product ID of Free Product
$allowedprdIds = array(38162, 38157);
$is_freeGift = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if (in_array($cart_item['product_id'], $prod_to_remove) && $cart_item['freeDosMas'] == 'yes'){
$is_freeGift = true;
}
if (in_array($cart_item['product_id'], $allowedprdIds) ){
$is_allowedPrd = true;
}
}
if($is_freeGift && !$is_allowedPrd){
foreach($prod_to_remove as $removeProduct => $id){
if (in_array($cart_item['product_id'], $prod_to_remove)) {
WC()->cart->remove_cart_item( $cart_item_key );
}
}
}
}
add_action( 'woocommerce_cart_item_removed', 'remove_gift_from_cart', 10, 2 );
Alright, got it!
By inserting a new product using WC()->cart->add_to_cart in the action woocommerce_add_to_cart function it creates a indefinite recursive loop which throws the error.
We can fix this by removing the add_to_cart action before inserting the new product:
remove_action('woocommerce_add_to_cart', __FUNCTION__);
(Showing technical difficulties if using add_to_cart() function)