Alter WooCommerce payment methods based on shipping

A few days ago we struggled with a WooCommerce webshop which had a specific payment method which was only valid for pick-up the products in the store. It took a while before we figured out how to make this work. At first we had a javascript / jQuery approach which did the job, but wasn’t that flexible and could lead to conflicts on different themes etc.

Thanks to a lot of Googling (we love that word) we found the solution which we’re going to share with you! The code below works for WooCommerce 2.1 and above.

How to change allowed payment based on selected shipping method

It’s easy to change which payment methods are allowed if you know how WooCommerce handles payment methods and shipping methods. You can use the code below in your (child) theme functions.php or in a custom plugin. In below code we remove the “Cheque” payment method (WC_Gateway_Cheque) when “Local Pick up” is NOT selected.

* Change payment methods based on shipping methods
function wpf_alter_payment_method($list){

// Get all available shipping methods
$chosen_rates = ( isset( WC()->session ) ) ? WC()->session->get( 'chosen_shipping_methods' ) : array();

// Check if the specific shipping_method ID is chosen.
if(!in_array( 'local_pickup', $chosen_rates ) ) { // Change "local_pickup".

// Remove specific payment method from list. In this case "WC_Gateway_Cheque"
$array_diff = array('WC_Gateway_Cheque'); // Change "WC_Gateway_Cheque"
$list = array_diff( $list, $array_diff );
return $list;
add_action('woocommerce_payment_gateways', 'wpf_alter_payment_method');

If you’ve a question about how to change the payment method based on selected shipping method you can add your comment below!