Search code examples
phpwordpresswoocommercegeolocationproduct

Avoid accessing specific products based on WooCommerce geolocated country


I the code below, I am able to hide specific products for a specific country using WooCommerce WC_Geolocation Class:

add_action( 'woocommerce_product_query', 'bbloomer_hide_product_if_country_new', 9999, 2 );
function bbloomer_hide_product_if_country_new( $q, $query ) {
    if ( is_admin() ) return;
    $location = WC_Geolocation::geolocate_ip();
    $hide_products = array( 17550, 32 );   
    $country = $location['country'];   
    if ( $country === "US" ) {
        $q->set( 'post__not_in', $hide_products );
    } 
}

The code works fine and hides the products based on the geolocated country in shop / category and search results on the front-end.

But the products are still visible if someone uses a direct link. How to avoid customers accessing directly specific single product pages too?


Solution

  • Replace all your code with the following:

    // Conditional custom function: check for geolocated countries (array)
    function is_targeted_geo_country( $countries ) {
        $location = WC_Geolocation::geolocate_ip();
        return in_array( $location['country'], $countries );
    }
    
    // Hide specific products from catalog
    add_action( 'woocommerce_product_query', 'hide_product_for_geo_countries', 9999, 2 );
    function hide_product_for_geo_countries( $q, $query ) {
        if ( is_admin() ) return;
    
        $product_ids = array( 17550, 32 );  // Here set the product to hide  
      
        if ( is_targeted_geo_country( array('US') ) ) {
            $q->set( 'post__not_in', $hide_products );
        } 
    }
    
    // Avoid accessing specific products, redirecting to shop
    add_action( 'template_redirect', 'redirect_to_shop_products_for_geo_countries' );
    function redirect_to_shop_products_for_geo_countries() {
        $product_ids = array( 17550, 32 );  // Here set the products to hide  
      
        if ( is_targeted_geo_country( array('US') ) && in_array( get_the_ID(), $product_ids ) ) {
            wp_safe_redirect( get_permalink( wc_get_page_id( 'shop' ) ) );
            exit();
        } 
    }