根据用户国家和产品 ID 自定义添加到购物车按钮

Customizing ADD TO CART buttons based on user country and product Ids

在我的 WooCommerce 商店中,我有一些产品仅在美国有售,我想在地理定位找到美国以外的任何国家/地区时隐藏单个产品页面上的 "Add to Cart" 按钮。

如果是美国,显示"add to cart', if it is not USA, hide "添加到购物车”按钮。

(P.S。我为此使用了一个插件,但由于某些 javascript 与其他插件的冲突,它不起作用。)

当条件匹配时(特定产品 ID 和其他国家/地区),此代码会将商店档案中的添加到购物车按钮替换为产品的 link,并在单个产品页面中替换为自定义文本。

You just need to set in:

  • 1st function the needed country code … (for you 'US' and already done)
  • 2nd and 3rd functions your product IDs in the array

代码如下:

// Conditional function country code detection
// @argument $code (string): country code restriction
// @return boolean
if( ! function_exists('is_from_country_code') ){

    // ==> HERE below set your country code (Replace 'US' by yours)
    function is_from_country_code( $code = 'US' ){
        $location = new WC_Geolocation;
        $user_ip = $location->get_ip_address();
        $user_country_code = $location->geolocate_ip( $user_ip, false, false )['country'];
        return $user_country_code == $code ? true : false;
    }
}

// Replace "Add to cart" single product button and quantity by a custom text
add_action( 'woocommerce_single_product_summary', 'Custom_single_add_to_cart', 1 );
function Custom_single_add_to_cart(){
    global $product;

    // Set here your product IDS
    $product_ids = array( 56, 53, 50 );

    if( is_from_country_code() ||
         ( ! is_from_country_code() && ! in_array( $product->get_id(), $product_ids) ) )
        return; // Continue for foreign countries and the specific products IDs

    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    add_action('woocommerce_single_product_summary', function(){
        echo '<p class="custom-text">'.__('Not available for your country', 'woocommerce').'</p>';
    }, 30);
}

// Shop and archives pages: we replace the button add to cart by a link to the product
add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_text_replace_button', 10, 2 );
function custom_text_replace_button( $button, $product  ) {

    // Set here your product IDS
    $product_ids = array( 56, 53, 50 );

    if( is_from_country_code() ||
         ( ! is_from_country_code() && ! in_array( $product->get_id(), $product_ids) ) )
        return $button; // Continue for foreign countries and the specific products IDs

    $button_text = __("View product", "woocommerce");
    return '<a class="button" href="'.$product->get_permalink().'">'.$button_text.'</a>';
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

此代码已在 woocommerce 版本 3+ 上测试并有效