If an online store sells fitness or weight-based equipment then offering discounts based on weight can be a unique selling proposition. This code snippet adds a BOGO “Buy One Get One” offer based on individual product weight when the products added to the cart meet the weight threshold as specified in the code.
add_action('woocommerce_cart_calculate_fees', 'ts_add_free_gift_based_on_product_weight', 10, 1); function ts_add_free_gift_based_on_product_weight($cart) { // Check if the cart is not empty if (!$cart->is_empty()) { // Set the weight threshold for the free gift $weight_threshold = 10; // Adjust this value to your specific requirement // Set the free gift product ID $free_gift_product_id = 470; // Change this to your actual free gift product ID // Initialize a flag to check if the free gift is already in the cart $free_gift_in_cart = false; // Iterate through each item in the cart foreach ($cart->get_cart() as $cart_item) { // Check if the product has weight information if (!empty($cart_item['data']->get_weight())) { // Check if the product weight is greater than or equal to the threshold if ($cart_item['data']->get_weight() >= $weight_threshold) { // Check if the free gift is not already in the cart if (!in_array($free_gift_product_id, array_column($cart->get_cart(), 'product_id'))) { $free_gift_in_cart = true; break; // Exit the loop if a qualifying product is found } } } } // If a qualifying product is found, add the free gift to the cart if ($free_gift_in_cart) { $cart->add_to_cart($free_gift_product_id, 1, 0, array(), array('free_gift' => true)); // Displaying a custom notice (optional) wc_clear_notices(); wc_add_notice(__('Free gift added to your cart based on product weight!'), 'notice'); } } }
Output
Let’s look into how each product’s weight is set in the admin interface.
- Log in to the admin dashboard and navigate to products.
- From the list of products, hover over a particular product and click on ‘edit’.
- From the product edit screen, scroll down to Product data and select “Shipping”.
- Within the “Shipping” tab, you’ll find the “Weight” field. Enter the weight of the product as you prefer.
Below is an example of setting the product weight to 5kg for a specific product “Barbell Gym Equipment”.
The products added to the cart below each holds a weight of 5 kg, less than the defined weight (i.e. threshold weight =10). Even though the total threshold weight is met, the free product doesn’t get added as the code works to check only based on individual product weight.
The product ‘LED Television’ has been assigned a weight of 12kg. So, when a product that meets the threshold weight is added to the cart, the free product is also automatically added for such products.
Similarly, you can also add bogo buy one get offer based on product dimensions in WooCommerce.