1

我有一个来自这里的用户帮助我并帮助我正确修复我的代码以使其正常运行,而上面的内容确实适用于自定义字段为 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;
}

我试图强制 Free Shipping 覆盖免费送货的最低金额,同时仍然根据 meta key 的 meta value 隐藏所有送货选项'auto_delivery_default'


编辑:

最后我发现它是自定义购物车项目数据
目标键delivery_options3 months.

4

1 回答 1

2

更新 2:

delivery_options当具有自定义数据的购物车商品的值为时,以下代码将强制执行“免费送货”方法3 months

// 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 文件中。测试和工作。

需要暂时刷新运输缓存,在“运输选项”选项卡下的 Woocommerce 全球运输设置中启用“调试模式” 。一旦测试并工作,只需禁用它,一切仍然有效。

于 2018-09-20T18:58:32.133 回答