Search code examples
phpwordpresswoocommercegeolocation

Show prices only for a specific customer's country in Woocommerce


I've developed a catalogue using woocommerce, however I need to be able to hide product prices from users who are visiting the site from outside of the UK due to reasons outside of my control.

I've found plugins that allow me to change product prices based on visitor location, but nothing allows me to hide the prices.

Is there any plugins that I've missed or anything I can add in to the woocommerce files to achieve this?


Solution

  • You can use the dedicated WooCommerce WC_Geolocation() Class, but you need to enable this feature in WooCommerce settings.

    The following will hide prices outside United kingdom based on customer geolocated country:

    add_filter( 'woocommerce_get_price_html', 'country_geolocated_based_hide_price', 10, 2 );
    function country_geolocated_based_hide_price( $price, $product ) {
        // Get an instance of the WC_Geolocation object class
        $geo_instance  = new WC_Geolocation();
        // Get geolocated user geo data.
        $user_geodata = $geo_instance->geolocate_ip();
        // Get current user GeoIP Country
        $country = $user_geodata['country'];
    
        return $country !== 'GB' ? '' : $price;
    }
    

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


    If you want to enable that geolocated feature only for unlogged customers, use the following:

    add_filter( 'woocommerce_get_price_html', 'country_geolocated_based_hide_price', 10, 2 );
    function country_geolocated_based_hide_price( $price, $product ) {
        if( get_current_user_id() > 0 ) {
            $country = WC()->customer->get_billing_country();
        } else {
            // Get an instance of the WC_Geolocation object class
            $geo_instance  = new WC_Geolocation();
            // Get geolocated user geo data.
            $user_geodata = $geo_instance->geolocate_ip();
            // Get current user GeoIP Country
            $country = $user_geodata['country'];
        }
        return $country !== 'GB' ? '' : $price;
    }
    

    An updated version of this code is available on this answer avoiding a backend bug.

    I have added in the function on start:

    if ( is admin() ) return $price;
    

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