You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce/WCFM:隐藏购物车无价格配送方式且保留免费配送

解决:保留免费配送,隐藏无价格的配送方式

需求与问题

  • 要隐藏购物车中未标注价格的配送方式
  • 现有代码会误隐藏「Free Shipping(免费配送)」,需调整让免费配送始终显示

原代码

function ts_hide_shipping_without_prices( $rates ) {
    foreach ( $rates as $rate_id => $rate ) {
        // Check if the cost is zero and the method is not free
        if ( 0 == $rate->cost && 'free_shipping' !== $rate->method_id ) {
            unset( $rates[ $rate_id ] );
        }
    }
    return $rates;
}

add_filter( 'woocommerce_package_rates', 'ts_hide_shipping_without_prices', 100 );

修改后的代码

function ts_hide_shipping_without_prices( $rates ) {
    foreach ( $rates as $rate_id => $rate ) {
        // 仅隐藏:非免费配送 且 配送成本为0(无标注价格)的选项
        if ( 'free_shipping' !== $rate->method_id && 0 == $rate->cost ) {
            unset( $rates[ $rate_id ] );
        }
    }
    return $rates;
}

add_filter( 'woocommerce_package_rates', 'ts_hide_shipping_without_prices', 100 );

关键说明

原代码逻辑本身没问题,若你的免费配送仍被隐藏,大概率是该配送方式的method_id不是free_shipping。可通过以下调试代码确认实际ID:

function ts_hide_shipping_without_prices( $rates ) {
    // 调试:打印所有配送方式的ID和成本,日志存于WordPress错误日志
    foreach ( $rates as $rate_id => $rate ) {
        error_log( '配送方式ID:' . $rate->method_id . ',成本:' . $rate->cost );
    }

    foreach ( $rates as $rate_id => $rate ) {
        // 替换为你查到的免费配送实际ID
        if ( 'free_shipping' !== $rate->method_id && 0 == $rate->cost ) {
            unset( $rates[ $rate_id ] );
        }
    }
    return $rates;
}

add_filter( 'woocommerce_package_rates', 'ts_hide_shipping_without_prices', 100 );

查看WordPress错误日志找到免费配送的method_id,替换代码中对应的字符串即可。

内容的提问来源于stack exchange,提问作者Mateusz Kulesza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 02:33:32