Search code examples
phpwordpresswoocommercecheckoutpayment-method

WooCommerce: Disable multiple Payment methods based on country


What I am trying to do here is hide payments methods, based on the customer country.

  • Hide bacs and cheque, when the country is different than US.

  • When the country is US, hide cod payment method (this is working)

I been trying to do this, but it didn't work

Here is the code:

add_filter( 'woocommerce_available_payment_gateways', 'custom_payment_gateway_disable_country' );
  
function custom_payment_gateway_disable_country( $available_gateways ) {
    if ( is_admin() ) return $available_gateways;
    if ( isset( $available_gateways['bacs' && 'cheque'] ) && WC()->customer->get_billing_country() <> 'US' ) {
        unset( $available_gateways['bacs' && 'cheque'] );
    } else {
        if ( isset( $available_gateways['cod'] ) && WC()->customer->get_billing_country() == 'US' ) {
            unset( $available_gateways['cod'] );
        }
    }
    return $available_gateways;
}

Can someone push me in the right direction? Any help will be appreciated!


Solution

  • Your if/else statements are wrong. As isset( $available_gateways['bacs' && 'cheque'] will never work.

    See: PHP If Statement with Multiple Conditions

    So you get:

    function filter_woocommerce_available_payment_gateways( $payment_gateways ) {
        // Not on admin
        if ( is_admin() ) return $payment_gateways;
    
        // Get country
        $customer_country = WC()->customer->get_shipping_country() ? WC()->customer->get_shipping_country() : WC()->customer->get_billing_country();
        
        // Country = US
        if ( in_array( $customer_country, array( 'US' ) ) ) {       
            // Cod
            if ( isset( $payment_gateways['cod'] ) ) {
                unset( $payment_gateways['cod'] );
            }
        } else {
            // Bacs & Cheque
            if ( isset( $payment_gateways['bacs'] ) && isset( $payment_gateways['cheque'] ) ) {
                unset( $payment_gateways['bacs'] );
                unset( $payment_gateways['cheque'] );
            }       
        }
        
        return $payment_gateways;
    }
    add_filter( 'woocommerce_available_payment_gateways', 'filter_woocommerce_available_payment_gateways', 10, 1 );