You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在WooCommerce购物车与结账页面为各配送方式显示自定义消息

嘿,Mark,我来帮你搞定这个需求!针对WooCommerce中选中不同配送方式时显示自定义消息的需求,我们可以通过钩子函数结合会话数据实现,同时覆盖购物车和结账页面,还能处理AJAX刷新的场景。下面是完整的实现方案:

解决方案

1. 核心代码实现

这段代码会在购物车和结账页面,根据当前选中的配送方式自动显示对应的自定义消息。你需要替换代码中的配送方式标识和对应的消息内容:

// 定义配送方式与自定义消息的映射关系
function get_shipping_method_custom_messages() {
    return array(
        'flat_rate:1' => '这是平邮配送的专属提示:预计3-5个工作日送达,偏远地区可能延迟',
        'free_shipping:2' => '恭喜选择免运费配送!订单将在2个工作日内发出,全程物流跟踪',
        'local_pickup:3' => '你选择了到店自提,请在下单后3天内携带订单凭证前往门店取货',
        'express_shipping:4' => '加急配送服务:当日16点前下单次日可达,仅限市区范围'
        // 可继续添加更多配送方式标识和对应消息
    );
}

// 在购物车页面的配送区域后显示消息
add_action( 'woocommerce_cart_totals_after_shipping', 'display_shipping_method_message_cart' );
function display_shipping_method_message_cart() {
    $messages = get_shipping_method_custom_messages();
    $chosen_method = WC()->session->get('chosen_shipping_methods')[0] ?? '';
    
    if( isset( $messages[$chosen_method] ) ) {
        echo '<div class="shipping-method-notice notice notice-info">';
        echo wp_kses_post( $messages[$chosen_method] );
        echo '</div>';
    }
}

// 在结账页面的配送区域后显示消息
add_action( 'woocommerce_review_order_after_shipping', 'display_shipping_method_message_checkout' );
function display_shipping_method_message_checkout() {
    $messages = get_shipping_method_custom_messages();
    $chosen_method = WC()->session->get('chosen_shipping_methods')[0] ?? '';
    
    if( isset( $messages[$chosen_method] ) ) {
        echo '<div class="shipping-method-notice notice notice-info">';
        echo wp_kses_post( $messages[$chosen_method] );
        echo '</div>';
    }
}

// 处理AJAX刷新时的消息更新(购物车/结账切换配送方式时自动刷新)
add_action( 'woocommerce_update_order_review_fragments', 'refresh_shipping_message_fragment' );
function refresh_shipping_message_fragment( $fragments ) {
    ob_start();
    display_shipping_method_message_checkout(); // 复用结账页面的显示逻辑
    $fragments['.shipping-method-notice'] = ob_get_clean();
    
    return $fragments;
}

2. 如何获取配送方式标识?

你需要替换代码中的flat_rate:1这类标识,获取方式如下:

  • 登录WordPress后台,进入WooCommerce > 设置 > 配送
  • 点击目标配送方式(比如「平邮」)进入编辑页
  • 浏览器地址栏会显示类似post=123&action=edit的参数,其中数字是配送方式ID
  • 完整标识格式为「配送类型:ID」,例如平邮是flat_rate:123,免运费是free_shipping:456

3. 自定义消息样式(可选)

如果想让消息更美观,可以在主题的style.css文件中添加样式:

.shipping-method-notice {
    padding: 12px 16px;
    margin: 10px 0;
    background-color: #f8f9fa;
    border-left: 4px solid #007cba;
    border-radius: 4px;
}

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

火山引擎 最新活动