【问题标题】:Avoid accessing specific products based on WooCommerce geolocated country避免访问基于 WooCommerce 地理定位国家/地区的特定产品
【发布时间】:2021-02-27 10:11:11
【问题描述】:

通过下面的代码,我可以使用 WooCommerce WC_Geolocation 类隐藏特定国家/地区的特定产品:

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 );
    } 
}

代码运行良好,并根据商店/类别中的地理定位国家/地区隐藏产品,并在前端搜索结果。

但如果有人使用直接链接,产品仍然可见。如何避免客户也直接访问特定的单品页面?

【问题讨论】:

    标签: php wordpress woocommerce geolocation product


    【解决方案1】:

    将所有代码替换为以下内容:

    // 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();
        } 
    }
    

    【讨论】:

    • 先生,代码的第三部分不起作用,它说重定向太多次。
    • @HannahJames 抱歉,我忘记了一些事情。更新。如果这个答案回答了你的问题,你可以请accept回答,如果你喜欢/想要你也可以请upvote回答,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 2018-07-23
    • 1970-01-01
    • 2013-11-30
    相关资源
    最近更新 更多