Woocommerce 中自定义购物车项目数据值的强制免费送货方法

Force free shipping method for custom cart item data value in Woocommerce

我有一位来自这里的用户帮助我并协助正确修复我的代码以使其正常运行,而上述内容适用于自定义字段为 90 天的所有内容以隐藏所有运输并仅显示“免费送货” “ 如果可供使用的话。但是,我的客户还设置了只显示一定数量的免费送货。

我想知道是否可以添加以下内容;

这是我正在使用的

add_filter( 'woocommerce_package_rates', 'show_only_free_shipping_for_autodelivery', 100, 2 );
function show_only_free_shipping_for_autodelivery ( $rates, $package ) {
    // Loop through cart items
    foreach( $package['contents'] as $cart_item ){
        if( $cart_item['data']->get_meta('auto_delivery_default') == '90 Days' ) {
            $found = true;
            break; // Stop the loop
        }
    }

    if( ! ( isset($found) && $found ) )
        return $rates; // Exit

    $free = array();
    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $free[ $rate_id ] = $rate;
            break;
        }
    }
    return ! empty( $free ) ? $free : $rates;
}

我试图强制免费送货覆盖免费送货的最低金额,同时仍然根据元键 'auto_delivery_default' 的元值隐藏所有送货选项。


Edit:

Finally I have discovered that it is custom cart item data:
The targeted key is delivery_options for a value of 3 months.

更新 2:

当带有自定义数据 delivery_options 的购物车商品的值为 3 months 时,以下代码将强制执行 "Free shipping" 方法:

// Conditionally hide others shipping methods when free shipping is available
add_filter( 'woocommerce_package_rates', 'show_only_free_shipping_for_autodelivery', 100, 2 );
function show_only_free_shipping_for_autodelivery ( $rates, $package ) {
    // Loop through cart items
    foreach( $package['contents'] as $cart_item ){
        if( isset($cart_item['delivery_options']) && $cart_item['delivery_options'] == '3 months' ) {
            $found = true;
            break; // Stop the loop
        }
    }

    if( ! ( isset($found) && $found ) )
        return $rates; // Exit

    $free = array();
    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $free[ $rate_id ] = $rate;
            break;
        }
    }
    return ! empty( $free ) ? $free : $rates;
}


// Force free shipping for a specific custom field value
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'filter_free_shipping_is_available', 20, 3 );
function filter_free_shipping_is_available ( $is_available, $package, $free_shipping ) {
    // Loop through cart items
    foreach( $package['contents'] as $cart_item ){
        if( isset($cart_item['delivery_options']) && $cart_item['delivery_options'] == '3 months' ) {
            $is_available = true;
            break; // Stop the loop
        }
    }

    return $is_available;
}

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

Refreshing shipping caches temporarily is needed, enabling the "Debug mode" in Woocommerce global shipping settings under "Shipping options" tab.
Once tested and working, just disable it and everything will still work.