避免在 Woocommerce 中针对特定国家/地区的特定产品结账
Avoid checkout for specific products on specific country in Woocommerce
这是我想要做的:
如果客户选择加拿大作为发货国家,并且购物车中有特定产品,则不应进行结帐,并且应生成一条错误消息,告知客户未进行结帐的原因。
我的研究:
has code to generate WooCommerce error messages. I asked a question yesterday that gave me codes to check if certain product is in cart and if shipping country is set to Canada 我不确定我必须将我的代码挂接到哪个 filter/action,以便它在结帐页面上单击 "Place Order" 时运行。
更新:
因此,我尝试将我在 my research 中列出的两个代码结合起来,但没有成功。如果我需要以不同的方式处理此问题,我们将不胜感激
产品 ID 为 15631 和 12616
这可以通过这个自定义函数使用操作挂钩 woocommerce_check_cart_items
来完成:
add_action( 'woocommerce_check_cart_items', 'products_not_shipable_in_canada' );
function products_not_shipable_in_canada() {
// Only on checkout page (allowing customer to change the country in cart shipping calculator)
if( ! is_checkout() ) return;
// Set your products
$products = array(15631, 12616);
// Get customer country
$country = WC()->session->get('customer')['shipping_country'];
if( empty($country) ){
$country = WC()->session->get('customer')['billing_country'];
}
// For CANADA
if( $country == 'CA' ){
// Loop through cart items
foreach( WC()->cart->get_cart() as $item ){
// IF product is in cart
if( in_array( $item['product_id'], $products ) ){
// Avoid checkout and display an error notice
wc_add_notice( sprintf(
__("The product %s can't be shipped to Canada, sorry.", "woocommerce" ),
'"' . $item['data']->get_name() . '"'
), 'error' );
break; // Stop the loop
}
}
}
}
代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。
相关:
这是我想要做的:
如果客户选择加拿大作为发货国家,并且购物车中有特定产品,则不应进行结帐,并且应生成一条错误消息,告知客户未进行结帐的原因。
我的研究:
更新:
因此,我尝试将我在 my research 中列出的两个代码结合起来,但没有成功。如果我需要以不同的方式处理此问题,我们将不胜感激
产品 ID 为 15631 和 12616
这可以通过这个自定义函数使用操作挂钩 woocommerce_check_cart_items
来完成:
add_action( 'woocommerce_check_cart_items', 'products_not_shipable_in_canada' );
function products_not_shipable_in_canada() {
// Only on checkout page (allowing customer to change the country in cart shipping calculator)
if( ! is_checkout() ) return;
// Set your products
$products = array(15631, 12616);
// Get customer country
$country = WC()->session->get('customer')['shipping_country'];
if( empty($country) ){
$country = WC()->session->get('customer')['billing_country'];
}
// For CANADA
if( $country == 'CA' ){
// Loop through cart items
foreach( WC()->cart->get_cart() as $item ){
// IF product is in cart
if( in_array( $item['product_id'], $products ) ){
// Avoid checkout and display an error notice
wc_add_notice( sprintf(
__("The product %s can't be shipped to Canada, sorry.", "woocommerce" ),
'"' . $item['data']->get_name() . '"'
), 'error' );
break; // Stop the loop
}
}
}
}
代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。
相关: