This guide is to tie a BOGO offer to specific shipping methods so that online store owners can influence customers to use a specified shipping method. Also, providing additional items such as gift wrappers or free samples which will make the purchase more personalized.
The code snippet given below will help to offer a free gift when the specified shipping methods defined in the array is selected by the customers.
add_action('woocommerce_cart_calculate_fees', 'ts_add_free_product_based_on_shipping', 20, 1); function ts_add_free_product_based_on_shipping($cart) { if (is_admin() && !defined('DOING_AJAX')) return; $chosen_shipping_method_id = WC()->session->get('chosen_shipping_methods')[0]; $chosen_shipping_method = explode(':', $chosen_shipping_method_id)[0]; // Set your free product ID $free_product_id = 470; // Only add the free product for specific shipping methods $allowed_shipping_methods = array('free_shipping', 'flat_rate'); // Add your allowed shipping methods here if (in_array($chosen_shipping_method, $allowed_shipping_methods)) { $product_already_in_cart = wc_find_product_in_cart($free_product_id); if (!$product_already_in_cart) { WC()->cart->add_to_cart($free_product_id, 1); } } else { // Check if the free product is in the cart $cart_item_key = wc_find_product_in_cart($free_product_id); if ($cart_item_key) { // Remove the free product from the cart WC()->cart->remove_cart_item($cart_item_key); } } } // Helper function to find a product in the cart function wc_find_product_in_cart($product_id) { foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) { if ($product_id == $cart_item['product_id']) { return $cart_item_key; } } return false; }
Output
When either of the shipping methods as defined in the code is selected, only then the free product gets added to the cart as shown in the image. In case of changing the chosen shipping method, will remove the free product that was added.
In case, if any other shipping method other than the specified shipping method is chosen, then the free product doesn’t get added as shown below.
Similarly, you can also add bogo buy one get one offer based on the chosen payment method in WooCommerce.