自定义添加到购物车按钮基于用户国家和产品ID
在我的WooCommerce商店,我有一些产品只在美国有售,我想隐藏单个产品页面上的“添加到购物车”按钮,当地理位置找到美国以外的任何国家。自定义添加到购物车按钮基于用户国家和产品ID
如果是美国,显示“添加到购物车”,如果不是美国,隐藏‘加入购物车’按钮。
(PS我用了一个插件,但它不工作一些JavaScript与其他插件冲突)
当条件匹配(特定产品ID和其他国家/地区)时,此代码将通过产品链接和单个产品页面中的商店归档中的购物车按钮替换自定义文本
你只需要设置:
- 1功能所需的国家代码...(你“美”,并已经完成)
- 第二和第三功能的产品ID阵列中
下面是代码:
// 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+和工作
非常感谢,我应该将它们添加到我的子主题的function.php中吗? – Tanvir
Hello,它现在为所有国家工作,美国或非美国,添加到购物车即使是美国,也不会显示,你可以再次检查plz。 – Tanvir
@Tanvir ... **好的测试,解决和更新(3)...这一次是永远好的** ...尝试它:) – LoicTheAztec
你的问题太模糊。请提供一些代码,屏幕截图和/或链接到你的页面 – vagelis
你好,我已经编辑了我的问题上面,你可以看看,我不知道我的functions.php中使用儿童主题代码。 – Tanvir
您可以提供单一产品页面类(或者表明它是美国的)和按钮“添加到购物车”ID或类吗? – vagelis