在 WooCommerce 中隐藏基于变体产品属性的运输方式

Hide shipping methods based on Variation product attribute in WooCommerce

在 WooCommerce 中,我有 两种运输方式 两个产品属性值 每个可变产品。客户应该 select 这些属性值之一才能将产品添加到购物车。

我正在尝试根据变体中 selected 的产品属性取消设置某些送货方式。例如,如果产品属性 'a' 被 selected,那么在购物车页面中应该只显示运输方式 1,如果产品属性 'b' 被 selected,运输方式 2 应该显示在购物车中。

我不知道该怎么做。

以下代码将隐藏基于产品变体产品属性条款定义的送货方式,在下面的代码中定义为设置:

add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_variation_product_attribute', 10, 2 );
function hide_shipping_method_based_on_variation_product_attribute( $rates, $package ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // HERE define the Product Attibute taxonomy (starts always with "pa_")
    $taxonomy = 'pa_color'; // Example for "Color"

    // HERE define shipping method rate ID to be removed from product attribute term(s) slug(s) (pairs) in this array
    $data_array = array(
        'flat_rate:12'      => array('blue'),
        'local_pickup:13'   => array('black', 'white'),
    );

    // Loop through cart items
    foreach( $package['contents'] as $cart_item ){
        if( isset($cart_item['variation']['attribute_'.$taxonomy]) ) {
            // The product attribute selected term slug
            $term_slug = $cart_item['variation']['attribute_'.$taxonomy];

            // Loop through our data array
            foreach( $data_array as $rate_id => $term_slugs ) {
                if( in_array($term_slug, $term_slugs) && isset($rates[$rate_id]) ) {
                    // We remove the shipping method corresponding to product attribute term as defined
                    unset($rates[$rate_id]);
                }
            }
        }
    }
    return $rates;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。

Refresh the shipping caches (required):

  1. This code is already saved on your function.php file.
  2. Check that the cart is empty…
  3. In a shipping zone settings, disable / save any shipping method, then enable back / save.

You are done and you can test it.