This type of customization allows store owners to tie BOGO “Buy One Get One” offers to specific payment methods in WooCommerce. The code dynamically adds a free product when a specific payment method is selected. You need to get the id of the payment method in WooCommerce and define that specific payment method ID as specified in the code given below.
add_action('woocommerce_cart_calculate_fees', 'ts_add_free_product_fee', 20, 1); function ts_add_free_product_fee($cart_object) { if (is_admin() && !defined('DOING_AJAX')) return; // Define your targeted payment method $targeted_payment_method = 'cheque'; // Define the free product ID $free_product_id = 470; // Replace with your actual free product ID $chosen_payment_method = WC()->session->get('chosen_payment_method'); // Check if the chosen payment method is the targeted one if ($targeted_payment_method === $chosen_payment_method) { // Check if the free product is not already in the cart if (!wc_find_product_in_cart($free_product_id)) { // Add the free product to the 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; } // Add jQuery to refresh payment methods on the checkout page add_action('woocommerce_review_order_before_payment', 'ts_refresh_payment_methods'); function ts_refresh_payment_methods() { ?> <script type="text/javascript"> (function ($) { $(document.body).on('change', 'input[name^="payment_method"]', function () { $('body').trigger('update_checkout'); }); })(jQuery); </script> <?php }
Output
In this output, when the particular payment method “cheque” is selected, the free gift gets added to the checkout page.
Similarly, you can also automatically add a product to your WooCommerce cart based on 6 different conditions covering cart total, categories, on website visit, and many more.