Ready to Transform Your Online Presence? Let's Get Started!

How to show/hide payment gateways according to checkout form data or customer data

If you are using Woocommerce with your WordPress site and on the checkout page you are allowing the customer to choose a payment gateway from multiple payment gateways but you want to hide or show specific payment gateways according to checkout form data. To achieve this you just have to use the code given below…

// Show/hide payment gateways
add_filter( 'woocommerce_available_payment_gateways', 'conditionally_hide_payment_gateways', 100, 1 );
function conditionally_hide_payment_gateways( $available_gateways ) {
    // 1. On Order Pay page
    if( is_wc_endpoint_url( 'order-pay' ) ) {
		if($_POST['state'] == 'TX' || $_POST['state'] == 'FL'){
			unset($available_gateways['stripe']);
			unset($available_gateways['yith_wcauthnet_credit_card_gateway']);
		}
		else if($_POST['state'] == 'CO' || $_POST['state'] == 'NM'){
			unset($available_gateways['cybersource']);
			unset($available_gateways['yith_wcauthnet_credit_card_gateway']);
		}
		else{
			unset($available_gateways['cybersource']);
			unset($available_gateways['stripe']);
		}
        
    }
    // 2. On Checkout page
    elseif( is_checkout() && ! is_wc_endpoint_url() ) {
        
        if($_POST['state'] == 'TX' || $_POST['state'] == 'FL'){
			unset($available_gateways['stripe']);
			unset($available_gateways['yith_wcauthnet_credit_card_gateway']);
		}
		else if($_POST['state'] == 'CO' || $_POST['state'] == 'NM'){
			unset($available_gateways['cybersource']);
			unset($available_gateways['yith_wcauthnet_credit_card_gateway']);
		}
		else{
			unset($available_gateways['cybersource']);
			unset($available_gateways['stripe']);
		}
    }
    return $available_gateways;
}

Add the above code somewhere in the functions.php file of your currently active WordPress theme.

In this above code as you can see we are unsetting some payment gateways according to the ‘state‘ selected by the customer on the checkout page.