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

如何通过woocommerce_cart_contents_changed钩子在购物车页面显示提示文本

解决WooCommerce购物车内容变化后显示自定义提示的问题

直接在woocommerce_cart_contents_changed钩子中echo内容会导致输出位置错误(通常会在页面最顶部甚至DOCTYPE之前),破坏页面结构。正确的做法是利用WooCommerce的会话存储提示信息,再在购物车页面的合适位置输出。

实现步骤

1. 监听购物车变化,存储提示信息

通过woocommerce_cart_contents_changed钩子检查特定产品的状态(添加/移除),并将提示信息存入WooCommerce会话:

add_action('woocommerce_cart_contents_changed', 'check_specific_cart_product_status', 10, 1);
function check_specific_cart_product_status($cart_contents) {
    // 替换为你的目标产品ID
    $target_product_id = 123;
    $session = WC()->session;

    // 获取上一次检查的产品存在状态
    $prev_product_exists = $session->get('target_product_prev_status', false);
    // 检查当前购物车中是否存在目标产品
    $current_product_exists = false;
    foreach ($cart_contents as $item) {
        if ($item['product_id'] === $target_product_id) {
            $current_product_exists = true;
            break;
        }
    }

    // 根据状态变化设置对应提示
    if ($current_product_exists && !$prev_product_exists) {
        $session->set('custom_cart_notice', '您已成功添加特定产品至购物车');
    } elseif (!$current_product_exists && $prev_product_exists) {
        $session->set('custom_cart_notice', '特定产品已从购物车中移除');
    }

    // 更新会话中的状态,用于下次对比
    $session->set('target_product_prev_status', $current_product_exists);
}

2. 在购物车页面输出提示信息

选择购物车页面的合适钩子(比如woocommerce_before_cart),读取会话中的提示并输出,显示后清除会话内容避免重复提示:

add_action('woocommerce_before_cart', 'display_custom_cart_notice');
function display_custom_cart_notice() {
    $session = WC()->session;
    $notice = $session->get('custom_cart_notice');

    if (!empty($notice)) {
        // 使用WooCommerce自带的消息样式输出
        wc_print_notice($notice, 'notice');
        // 清除会话中的提示,防止刷新页面重复显示
        $session->__unset('custom_cart_notice');
    }
}

调整提示位置

如果你想把提示放在购物车页面的其他位置,只需替换woocommerce_before_cart为以下钩子之一:

  • woocommerce_cart_contents_before:购物车商品列表上方
  • woocommerce_after_cart_table:购物车表格下方
  • woocommerce_after_cart:购物车页面底部

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 21:30:54