In this post, you can implement a BOGO promotion similar to one of our previous post which will implement a BOGO deal to buy a fixed total quantity from both categories X and Y, get one free from category Z. But here, we will be providing an option among the categories X and Y from which customers need to buy a fixed total quantity. The difference is that if any one of the categories meets the required quantity threshold then the free product is added from Category Z.
add_action('woocommerce_before_cart', 'ts_cart', 10); function ts_cart() { // Initialize variables $category_ids_to_buy = array(50, 65); // Categories X and Y $free_category_id = 63; // Category Z $required_quantity = 3; // Total combined quantity required to trigger free product // Initialize counters for each category $category_counts = array_fill_keys($category_ids_to_buy, 0); // Update counters based on items in the cart foreach (WC()->cart->get_cart() as $cart_item) { $cart_product_cats_ids = wc_get_product_term_ids($cart_item['product_id'], 'product_cat'); foreach ($category_ids_to_buy as $cat_id) { if (in_array($cat_id, $cart_product_cats_ids)) { $category_counts[$cat_id] += $cart_item['quantity']; } } } // Check if any category meets or exceeds the required quantity foreach ($category_counts as $category_id => $count) { if ($count >= $required_quantity) { // Get a free product from the specified category $free_product_id = ts_get_free_product_from_category($free_category_id); // If free product ID is not null, add it to the cart if ($free_product_id) { // Add free product to the cart WC()->cart->add_to_cart($free_product_id); } } } } function ts_get_free_product_from_category($category_id) { // Implement this function to dynamically get a free product ID from the specified category $args = array( 'post_type' => 'product', 'posts_per_page' => 1, 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'id', 'terms' => $category_id, ), ), ); $products_query = new WP_Query($args); if ($products_query->have_posts()) { $products_query->the_post(); $free_product_id = get_the_ID(); wp_reset_postdata(); return $free_product_id; } return null; // Return null if no free product is found } add_action('woocommerce_before_shop_loop', 'display_bogo_notice'); function display_bogo_notice() { echo '<div class="woocommerce-message">Choose any 3 from category "Smartphone" or "Laptops" and get one free product.</div>'; }
Output
To make customers aware of the BOGO Promotions running in your online store you can add a notice to prompt them and clearly mention the categories for which the BOGO offer is applied as shown below.
When customers choose the products from Category X and Category Y, and if the minimum required quantity of 3 is met, one of the free product from Category Z will be fetched and automatically added to the cart.
In the same way, you can also offer discounts on category Y when purchasing category X within a specified quantity range in WooCommerce.