Search code examples
javascriptphpajaxwordpresswoocommerce

WooCommerce - Deselect Default Payment Method


I am trying to get WooCommerce to not automatically select the first payment method on the checkout page.

This would force the customer to select a payment method on their own and neaten up the checkout page. At present, with the first payment method automatically selected lots of payment information relating to that method is shown to the customer and pushes the other payment methods down the page. On mobile this is a problem as some think this is the only method of payment due to stacking.

The below JS works in removing a default payment method being selected.

However, when I try to then select a payment method, it initially loads the gateway information but then disappears and the selection is removed. I suspect AJAX is causing an issue here due to how this section reloads. This makes it impossible to select a payment method.

Could anyone help expand on this code to allow a gateway selection ? Many Thanks

jQuery(document).ready(function( $ ){
    $( document ).on( 'updated_checkout', function() {
        var $paymentCheckboxes = $( ".woocommerce-checkout-payment" ).find( '[name="payment_method"]');
        $paymentCheckboxes.attr('checked', false);
        $('.payment_box').hide();
    });
});

Payment methods are all unselected, allowing a customer to see which methods are available better.


Solution

  • Please test with the below code. You need to use the 'updated_checkout' event to reset the payment gateway form after the "?wc-ajax=update_order_review" ajax call.

    jQuery(document).ready(function ($) {
        function deselectDefaultGateway() {
            $('input[name="payment_method"]').each(function (index, item) {
                $(item).attr('checked', false);
            })
            $('.payment_box').hide();
        }
    
        $(document.body).on('updated_checkout', deselectDefaultGateway);
    
        $(document).on('click', '.wc_payment_method', function(e){
            if (e.originalEvent !== undefined) {
                $(document.body).off('updated_checkout', deselectDefaultGateway);
            }
        });
    });
    

    And, for your information, to prevent default selection on loading you can use code like below.

    add_action( 'woocommerce_before_template_part', 'custom_before_template_part', 10, 4 );
    function custom_before_template_part($template_name, $template_path, $located, $args) {
        if ( 'checkout/payment-method.php' == $template_name ) {
            $gateway = $args['gateway'];
            $gateway->chosen = false;
        }
    }
    

    Woocommerce selects the first payment gateway as the default, but with the above 2 code blocks, you can completely change the behavior. Hope this would help you.