Search code examples
phpwordpresswoocommercegeolocationpayment-gateway

Disable all payment methods based on user country geo-ip in WooCommerce


In my Woocommerce shop I set up the geolocation system, when geolocation identifies any country other than IT I would like to disable payment methods

If it is IT (geop-ip), show payment methods

If all other country (geo-ip), disable all payment methods.


Solution

  • Woocommerce has already a geolocation Ip feature through WC_Geolocation class, so you don't need any additional plugin.

    Here is the way to disable payment gateways for all countries except "IT" (Italy) country code, based on costumer geolocated IP country:

    // Disabling payment gateways except for the defined country codes 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('IT');
    
        // 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 for all countries except the allowed defined coutries
        if ( ! in_array( $user_geolocation['country'], $allowed_country_codes ) )
            $available_gateways = array();
    
        return $available_gateways;
    }
    

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


    Related: