In some cases you would like to limit the payment gateways your WooCommerce store offers based on the customer’s billing country. The following code snippet uses the woocommerce_available_payment_gateways filter to accomplish this.
First, you will need to find and copy the payment gateway stub by going to: WP-Admin > WooCommerce > Settings > Payments > [select the gateway] then locate the stub in the address bar.
wp-admin/admin.php?page=wc-settings&tab=checkout§ion=[Payment Gateway Stub]
Then you can modify the following code snippet to your the functions.php file of your child theme or the code snippets plugin. Replace both {Payment Gateway Stub} with what you copied in the step above.
This is set up to include this gateway option for customers with a United States or Canadian billing address only; but, it can be modified to include or exclude based on any parameter.
add_filter( 'woocommerce_available_payment_gateways', 'gmc_payment_gateway_disable_country' );
function gmc_payment_gateway_disable_country( $available_gateways ) {
if ( is_admin() ) return $available_gateways;
if ( isset( $available_gateways['sagepaymentsusaapi'] )){
$billing_c = WC()->customer->get_billing_country() ?? array();
if(!in_array($billing_c, array('US','CA'))) {
unset( $available_gateways['sagepaymentsusaapi'] );
}
}
return $available_gateways;
}
This code is here for reference purposes only and is not intended for use in a production environment. Modify and use this code at your own risk.
EDIT: added $billing_c to default to an array in the event that get_billing_country() returns null.