Skip to content
Advertisement

Disable all payment gateways except BACS based on geo-ip country in Woocommerce

In Woocommerce, I am using the code made from this answer thread which enables ALL payment gateways if the user’s GEO IP is from an array of allowed countries. Here the allowed country code that I want is “SE” (Sweden).

What I would like is to disable all payment gateways except BACS to become available if the GEO IP is outside of Sweden (the pre-defined allowed country).

Any help is appreciated.

Advertisement

Answer

The following code will disable all available payment gateways except BACS for non allowed GEO IP defined countries (Here Sweden):

// Disabling payment gateways (except BACS) based on user IP geolocation country
add_filter( 'woocommerce_available_payment_gateways', 'geo_country_based_available_payment_gateways', 90, 1 );
function geo_country_based_available_payment_gateways( $available_gateways ) {
    // Not in backend (admin)
    if( is_admin() ) 
        return $available_gateways;

    // ==> HERE define your country codes
    $allowed_country_codes = array('SE');

    // Get an instance of the WC_Geolocation object class
    $geolocation_instance = new WC_Geolocation();
    // Get user IP
    $user_ip_address = $geolocation_instance->get_ip_address();

    // Get geolocated user IP country code.
    $user_geolocation = $geolocation_instance->geolocate_ip( $user_ip_address );

    // Disable payment gateways (except BACS) for all countries except the allowed defined countries
    if ( ! in_array( $user_geolocation['country'], $allowed_country_codes ) ){
        $bacs_gateways              = $available_gateways['bacs'];
        $available_gateways         = array();
        $available_gateways['bacs'] = $bacs_gateways;
    }

    return $available_gateways;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Related: Disable payment gateways based on user country geo-ip in Woocommerce

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement