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

Check variation items for specific string in the product name and allowed countries in WooCommerce

如何添加允许的国家/地区列表,以及如何定位标题中只有特定词的产品,而不是变体 ID。例如,“Framed A3 Poster”产品标题中的“framed”一词。

这意味着我可以避免定位每个单独的变体 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 文件。已测试并有效。