If your online store sells furniture items, electronic or sports goods, it’s essential to rely on the dimensions of the product and usually only discounts are offered for shipping oversized items. Now, you can also tie the BOGO offer to the physical attributes (such as dimensions) of these products. This code will help you to add a free product to the cart, specifically when a product with dimensions greater than 40x40x40 is present in the cart.
add_action('woocommerce_before_calculate_totals', 'ts_add_free_product_to_cart_if_large'); function ts_add_free_product_to_cart_if_large($cart) { // Check if any product in the cart has dimensions greater than 40*40*40 $has_large_product = false; foreach ($cart->get_cart() as $cart_item) { $product = wc_get_product($cart_item['product_id']); if ($product && $product->is_visible() && $product->get_length() > 40 && $product->get_width() > 40 && $product->get_height() > 40) { $has_large_product = true; break; } } // Add the free product to the cart if it's not already present and a large product is in the cart if ($has_large_product) { ts_add_free_product_to_cart(); } } // Function to add a free product to the cart function ts_add_free_product_to_cart() { $free_product_id = 470; // Replace with the actual ID of your free product $cart = WC()->cart; // Check if the free product is not already in the cart $free_product_in_cart = false; foreach ($cart->get_cart() as $cart_item) { if ($free_product_id == $cart_item['product_id']) { $free_product_in_cart = true; break; } } // Add the free product if it's not in the cart if (!$free_product_in_cart) { $cart->add_to_cart($free_product_id, 1); } }
Output
When a customer adds any product to the cart that has dimensions greater than 40x40x40 (length x width x height), the code will add a specified free product (identified by ID 730) to the cart.
You can consider various other factors to provide such BOGO offers. Refer to our post that will guide you well to automatically add a product to your WooCommerce cart based on 6 different conditions.