lilbiscuit lilbiscuit - 5 months ago 109
jQuery Question

Select Woocommerce payment method conditionally in PHP

I want to programmatically set a default payment method (radio is checked) in woocommerce checkout page based on a condition using php (not jquery).

Lets say I have two payment methods:

'pay_method1' and 'pay_method2'


Most solutions suggest removing a method in order to select the other:

unset($gateways['pay_method1']) //auto selects pay_method2 naturally


But I don't want to remove the method. I only want to set a default when the checkout page loads / reloads, so the the user can still switch methods if needed.

I plan on having the following action in
functions.php
:

add_action("woocommerce_before_checkout_form", "custom_before_checkout_action");
function custom_before_checkout_action() {

if ($my_condition) {
//default to pay_method1 - how??
}
else {
//default to pay_method2 - how??
}


}

Is this possible to tell woocommerce which payment method should be checked this way?

Answer

You can see woocommerce template structure checkout folder have file payment-method.php. There are payment method $gateway object have property $gateway->chosen to access true default checked payment gateway.

add_filter('woocommerce_available_payment_gateways', 'show_custom_payment_gateways');

    function show_custom_payment_gateways( $available_gateways){

      global $woocommerce;
      $available_gateways = $woocommerce->payment_gateways->get_available_payment_gateways();

      if( $myconditon ){
      $available_gateways['pay_method2']->chosen = true;
      $available_gateways['pay_method1']->chosen = false // default to false unchecked. 
    }

}

Comments