Suppose you own an online clothing store that consists of different product variations, colors, or styles, variation product. In that case, this post helps you to implement buy one, get one (BOGO) promotional offers, especially when certain product variations items are added to the cart. Such BOGO offers allow store owners control over which variation items are eligible for the promotion.
add_action('woocommerce_cart_calculate_fees', 'ts_add_free_product_on_bogo_offer', 10, 1); function ts_add_free_product_on_bogo_offer($cart) { if (is_admin() && !defined('DOING_AJAX')) { return; } // YOUR SETTINGS: $target_variable_product_id = 396; // ID of the variable product (Shirt) $target_variation_id = 411; // ID of the Blue Shirt variation $free_product_id = 470; // ID of the free product // Check if the targeted variation is in the cart $is_target_variation_in_cart = false; foreach ($cart->get_cart() as $cart_item) { if ($target_variable_product_id == $cart_item['product_id'] && $target_variation_id == $cart_item['variation_id']) { $is_target_variation_in_cart = true; break; } } // Add the free product to the cart if the targeted variation is found if ($is_target_variation_in_cart) { $found = false; // Check if the free product is not already in the cart if (sizeof($cart->get_cart()) > 0) { foreach ($cart->get_cart() as $cart_item_key => $values) { $_product = $values['data']; if ($_product->get_id() == $free_product_id) { $found = true; break; // Exit the loop } } // If the product is not found, add it to the cart if (!$found) { WC()->cart->add_to_cart($free_product_id); } } else { // If no products in the cart, add the free product WC()->cart->add_to_cart($free_product_id); } } }
Output
Let’s consider that a product ‘T- Shirt’ has 3 variations of color such as Blue, Green, and Red. As the product variations of Blue (variation_id: 411), and Green (variation_id: 412), are associated with the variable product with ID 396, and are defined in the code, when these products added to the cart, then the free products are also automatically added to the cart.
In the same way, you can apply BOGO offers considering many other factors as well. Refer to our post that will guide you well to automatically add a product to your WooCommerce cart based on 6 different conditions.