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

如何通过短代码在前端展示WooCommerce Shipping Zones完整信息?

我来帮你完善这个短代码,让它能展示你需要的所有配送区域信息~你之前的代码只输出了区域名称,是因为没去解析$the_zone里的其他字段,WooCommerce的get_zones()返回的数组里其实包含了区域的所有关键信息,咱们一步步把它们挖出来:

首先要注意:短代码不能直接用echo输出内容,不然会导致内容显示在页面错误的位置(比如页面顶部),所以咱们用输出缓冲来处理。下面是修改后的完整代码:

function shipping_zones_shortcode() { 
    ob_start(); // 开启输出缓冲,避免直接echo的位置问题
    $delivery_zones = WC_Shipping_Zones::get_zones(); 

    // 处理没有配送区域的情况
    if ( empty( $delivery_zones ) ) {
        echo '<p>暂无可用配送区域</p>';
        return ob_get_clean();
    }

    // 外层列表容器
    echo '<ul class="shipping-zones-list">';
    foreach ( (array) $delivery_zones as $the_zone ) { 
        // 1. 获取并转义区域名称
        $zone_name = esc_html( $the_zone['zone_name'] );

        // 2. 获取区域覆盖的国家/州,用WooCommerce自带方法格式化显示
        $zone_locations = $the_zone['zone_locations'];
        $formatted_locations = [];
        foreach ( $zone_locations as $location ) {
            $formatted_locations[] = $location->get_formatted_location();
        }
        $locations_str = implode( ', ', $formatted_locations );

        // 3. 获取该区域的所有配送方式及对应费用
        $shipping_methods = $the_zone['shipping_methods'];
        $methods_html = '<ul class="shipping-methods-list">';
        foreach ( $shipping_methods as $method ) {
            $method_title = esc_html( $method->get_title() );
            // 格式化配送费用,适配商店货币设置
            $method_cost = wc_price( $method->get_cost() );
            $methods_html .= "<li>{$method_title}: {$method_cost}</li>";
        }
        $methods_html .= '</ul>';

        // 拼接当前区域的HTML内容
        echo "<li>
            <strong>{$zone_name}</strong>
            <p>覆盖区域:{$locations_str}</p>
            <p>配送方式:</p>
            {$methods_html}
        </li>";
    }
    echo '</ul>';

    return ob_get_clean(); // 返回缓冲的内容作为短代码输出
} 
add_shortcode( 'list_shipping_zones', 'shipping_zones_shortcode', 10 );

代码说明:

  • 输出缓冲处理:用ob_start()和ob_get_clean()包裹输出逻辑,确保内容在短代码所在位置正确显示,而不是提前输出到页面顶部。
  • 安全转义:用esc_html()处理所有用户可见的文本,避免XSS安全风险。
  • 位置格式化:$location->get_formatted_location()是WooCommerce内置方法,能把后台设置的区域(比如国家代码、州代码)转换成用户友好的名称(比如“United States (US)”或“California, US”)。
  • 费用格式化:wc_price()会自动适配你的商店货币设置,把数字格式化成带符号的价格(比如$10.00)。如果你的配送方式是动态费用(比如基于重量、购物车金额),这个方法会返回基础费用,你可以根据实际需求调整逻辑。
  • 样式扩展:代码里加了shipping-zones-list和shipping-methods-list两个CSS类,方便你后续自定义列表的样式。

现在你只需要把短代码[list_shipping_zones]放到页面、文章或者小工具里,就能看到包含区域名称、覆盖范围、配送方式及费用的完整列表啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 13:07:48