在WooCommerce中检查产品名称和允许的国家/地区中的特定字符串的变体项目



如何添加允许的国家/地区、以及标题中只有特定单词的目标产品的列表,而不是变体id。例如,单词"框状";在";"带框A3海报";产品名称。

这意味着我将避免针对每个单独的变体id,因为我实际上有+280个产品。

下面的代码是我正在使用的:

add_action( 'woocommerce_check_cart_items', 'check_cart_items_for_shipping' );
function check_cart_items_for_shipping() {
$allowed_variation_id = '13021'; // Here defined the allowed Variation ID
$allowed_country      = 'IE'; // Here define the allowed shipping country for all variations
$shipping_country = WC()->customer->get_shipping_country();
$countries        = WC()->countries->get_countries();
// Loop through cart items
foreach(WC()->cart->get_cart() as $cart_item ) {
// Check cart item for defined product Ids and applied coupon
if( $shipping_country !== $allowed_country && $cart_item['variation_id'] !== $allowed_variation_id ) {
wc_clear_notices(); // Clear all other notices
// Avoid checkout displaying an error notice
wc_add_notice( sprintf( __('The product "%s" can not be shipped to %s.'),
$cart_item['data']->get_name(),
$countries[$shipping_country]
), 'error' );
break; // stop the loop
}
}
}

使用strpos()PHP函数将允许在购物车商品名称中查找字符串,如下所示(该代码还处理多个允许的国家代码(:

add_action( 'woocommerce_check_cart_items', 'check_cart_items_for_shipping' );
function check_cart_items_for_shipping() {
$string_to_find    = 'framed';    // The string to find in product variation name (in lower case)
$allowed_countries = array('IE'); // The allowed shipping country codes
$shipping_country  = WC()->customer->get_shipping_country(); // Customer shipping country
// Loop through cart items
foreach(WC()->cart->get_cart() as $item ) {
$product_name = $item['data']->get_name(); // Get the product name

// Check cart item for a defined string in the product name and allowed country codes
if( ! in_array( $shipping_country, $allowed_countries ) 
&& strpos( strtolower($product_name), $string_to_find ) === false ) {

wc_clear_notices(); // Clear other existing notices

$countries = WC()->countries->get_countries(); // Load WooCommerce countries
// Avoid checkout displaying an error notice
wc_add_notice( sprintf( __('The product "%s" can not be shipped to %s.'),
$product_name,
$countries[$shipping_country]
), 'error' );
break; // stop the loop
}
}
}

代码位于活动子主题(或活动主题(的functions.php文件中。测试并工作。

相关内容

最新更新