How to set payment method in Woocommerce via PHP

1.5k views Asked by At

I want to manually select payment method via PHP in a Woocommerce site.

Something like this:

$payment_method = 'authorize_net_aim'

Then when the customer hits checkout and sees the list payment options, the payment method that was set in PHP is auto-selected. The challenge is that woocommerce checkout.js runs ajax after the page is loaded. So any on-page stuff I've tried is overwritten.

I have reviewed the WC_Payment_Gateway class but don't see how to select a specific gateway using it's id (i.e. authorize_net_aim).

1

There are 1 answers

4
Domain On

The solution for this issue, i.e auto selecting a payment mode can be achieved using the following code.

add_action('woocommerce_review_order_before_submit','select_payment_mode_as_defined_here' ); function select_payment_mode_as_defined_here(){ echo '<script>jQuery("#authorize_net_aim").prop("checked", true);</script>'; }

Assumption is that 'authorize_net_aim' is the id of the radio option button.

I used this solution to select the PayPal method as default so set the id to '#payment_method_paypal' in jQuery() and it worked for me.

Lemme Know if it worked for you too. And whether this answer was useful or not.