This customization is to encourage customers to use a preferred payment method by dynamically adjusting the cart contents and also offering a discount based on the chosen payment method.
The code helps to automatically include a product in the cart with a 50% discount applied to the original product price when a specific payment method is chosen.
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 = 911; // Replace with your actual free product ID $discount_percentage = 50; // Replace with the desired discount percentage $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); // Apply the discount to the added free product foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) { if ($free_product_id == $cart_item['product_id']) { $discount_amount = $cart_item['data']->get_price() * $discount_percentage / 100; $cart_item['data']->set_price($cart_item['data']->get_price() - $discount_amount); break; } } } } 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
When the customer proceeds to the checkout page and selects the pre-defined payment method ‘Cheque’, the specified product in the code will be added to the cart with a 50% discount applied to its original price.
Similarly, you can try out different BOGO offers based on ‘N’ number of conditions. Check out this guide that will help you to automatically add a product to your WooCommerce cart.