WooCommerce Disable Payment Gateway Based On Shipping Method

WooCommerce payment gateway dependent shipping method

Pre-Requisites

You’ll need the shipping method radio button value and payment gateway ID you wish to disable.

How To Implement This Solution?

Simply copy the pre-coded solution to your active theme’s functions.php or preferably the Code Snippets Plugin.

About this Solution

If you do not have the facility to take payments other than cash for in-person shipping methods like local pickup, you may wish to disable the appropriate payment gateways and force the customer to pay by cash for example. This quick guide shows you how to do exactly that.

				
					/*
* Snippet Name:		Payment gateway dependent shipping methods
* Snippet Author:	ecommercehints.com
*/

add_filter('woocommerce_available_payment_gateways', 'ecommercehints_payment_dependent_delivery');

function ecommercehints_payment_dependent_delivery($gateways) {
	if(is_admin()) { 
		return $gateways;
	}
	
	if(is_wc_endpoint_url('order-pay')) {
		$order = wc_get_order(wc_get_order_id_by_order_key($_GET['key']));
		if($order->has_shipping_method('local_pickup')) {
			if(isset($gateways['cheque'])) { // Cheque payments will be disabled
				unset($gateways['cheque']);
			}
		}
		
	} else {
		$chosen_shipping_method = WC()->session->get('chosen_shipping_methods')[0];

		if ('local_pickup:2' === $chosen_shipping_method) { //shipping method radio button value
			if(isset($gateways['cheque'])) {
				unset($gateways['cheque']);
			}
		}		
	}
	
	return $gateways;
}
				
			

How Do I get The Payment Gateway Radio Button Value?

Use your browser dev tools to inspect the element. You are looking for the radio button’s value

WooCommerce get payment gateway id using inspect element

How Do I get the shipping method radio button value?

Again, use your browser dev tools to inspect the element. You are looking for the radio button’s value

Snippet Benefits

  • Force uses to pay by certain tender depending on the shipping method selected on the WooCommerce checkout.
WooCommerce Conversion Rate Optimisation (CRO) eBook
100 WooCommerce Conversion Rate Optimisation Tips

Leave a Reply

If you are going to write code in the comments, please wrap it between code tags.

Your email address will not be published. Required fields are marked *

Other Recent Guides

Subscribe To Emails

Get exclusive WooCommerce tips that I only share with email subscribers

Join hundreds of other subscribers