Search code examples
wordpresswoocommercepayment-gatewaypayment-method

want to check payment method on checkout page after a confirmation


I working on a Woocommerce project and my client asked me two things:

  1. Does not want to uncheck all the payment methods available on the checkout page.
  2. Wants to show a confirmation pop up( <script>confirm("Are you sure?")</script> ) on selecting 'cod' as payment method, after clicking 'no' or 'cancel' on the confirmation pop change the payment method as online payment or others accept 'cod'.

Please any help is appreciated.


Solution

  • I have managed to achieve what you need. I don't know whether it is the right way.

    add_action( 'woocommerce_review_order_before_payment', 'refresh_payment_methods' );
    
    function refresh_payment_methods(){
        ?>
        <script type="text/javascript">
            (function($){
                $( 'form.checkout' ).on( 'change', 'input[name^="payment_method"]', function(event) {
                    var payment_method = $('form.checkout').find('input[name^="payment_method"]:checked').val();
                    if(payment_method == 'cod'){
                        var method_select = confirm('Are you sure ?');
                        if(!method_select){
                            $('form.checkout').find('input[name^="payment_method"]').each(function(index, el) {
                                if($(this).val() == 'cod'){
                                    $(this).prop('checked',false);
                                }else{
                                    $(this).prop('checked',true);
                                }
                            });
    
                        }else{
                            $('body').trigger('update_checkout');   
                        }
                    }else{
                        $('body').trigger('update_checkout');
                    }
                });
            })(jQuery);
        </script>
        <?php
    }
    

    On changing the form input with name payment_method, the checked value is taken and comparing it with available payment methods. If the payment method is cod then corresponding checkbox is unchecked. (Since the code was too urgent for you, i couldn't make the else part perfect)