Home » WooCommerce: Hide Products Based on IP Address / Geolocation

WooCommerce: Hide Products Based on IP Address / Geolocation

by Tutor Aspire

There are many plugins that would allow you to do this in bulk or that would give you advanced features… but what if you just need to hide one product ID for users who are visiting your WooCommerce website from a specific country code?

This is also called “geolocation” – remember this won’t work unless you’ve enabled geolocation inside the WooCommerce general settings. Other than that, get your product ID, find out the target country 2-letter code, and this snippet will do the trick. Enjoy!

Case study: hiding a given product ID to users based in a specific country (IT)

PHP Snippet 1: Hide Product ID Based on Geolocated Country @ WooCommerce Shop

In the example below, I’m hiding product ID = 344 if the current visitor is from Italy. This PHP Snippet may give you pagination problems sometimes – if this fails, check out snippet 2 below.

/**
 * @snippet       Hide Product Based on IP Address
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 4.0
 * @donate $9     https://www.tutoraspire.com
 */

add_filter( 'woocommerce_product_is_visible', 'tutoraspire_hide_product_if_country', 9999, 2 );

function tutoraspire_hide_product_if_country( $visible, $product_id ){
$location = WC_Geolocation::geolocate_ip();
$country = $location['country'];
if ( $country === "IT" && $product_id === 344 ) {
$visible = false;
}
return $visible;
}

PHP Snippet 2 (Alternative): Hide Product ID Based on IP Address @ WooCommerce Shop

In this example, I’m hiding products 21 and 32 if the user is browsing from a USA IP address.

/**
 * @snippet       Hide Product Based on IP Address
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 4.0
 * @donate $9     https://www.tutoraspire.com
 */

add_action( 'woocommerce_product_query', 'tutoraspire_hide_product_if_country_new', 9999, 2 );

function tutoraspire_hide_product_if_country_new( $q, $query ) {
    if ( is_admin() ) return;
    $location = WC_Geolocation::geolocate_ip();
    $hide_products = array( 21, 32 );
    $country = $location['country'];
    if ( $country === "US" ) {
        $q->set( 'post__not_in', $hide_products );
    } 
}

You may also like