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

WooCommerce:购物车验证后打印通知前修改通知的钩子及替代方案

问题解答

一、购物车验证完成后、通知打印前修改所有通知的钩子

针对你遇到的商业插件替换woocommerce_before_cart为plugin_before_cart的情况,推荐两种解决方案:

1. 使用woocommerce_cart_loaded_from_session钩子

这个钩子会在购物车数据加载、验证逻辑全部完成后触发,此时所有购物车相关通知已生成,且早于wc_print_notices()执行。建议用较高优先级(比如20)确保所有通知都已生成:

add_action('woocommerce_cart_loaded_from_session', 'custom_modify_cart_notices', 20);
function custom_modify_cart_notices() {
    $notices = wc_get_notices();
    
    if (!empty($notices)) {
        // 在这里对$notices数组做自定义调整(修改内容、合并通知等)
        
        // 清空原有通知
        wc_clear_notices();
        
        // 重新添加修改后的通知
        foreach ($notices as $type => $messages) {
            foreach ($messages as $message) {
                wc_add_notice($message, $type);
            }
        }
    }
}

2. 针对plugin_before_cart的输出缓冲方案

如果上述钩子不生效,可利用输出缓冲捕获通知HTML并修改,绕开优先级问题:

add_action('plugin_before_cart', 'buffer_cart_notices', 9);
add_action('plugin_before_cart', 'modify_buffered_notices', 11);

function buffer_cart_notices() {
    ob_start();
}

function modify_buffered_notices() {
    $buffer = ob_get_clean();
    // 直接修改捕获到的通知HTML内容(替换文本、调整样式等)
    echo $buffer;
}

二、wc_add_notice()的替代方案

CartController.php的注释提示仅针对API场景:

  • 前端场景下,wc_add_notice()依然是合规用法,无需替换;
  • API场景下,需用WP_Error类生成可被API识别的错误对象:
// 创建WP Error对象
$error = new WP_Error(
    'cart_validation_fail', // 错误代码
    '自定义购物车验证错误提示', // 错误消息
    array('status' => 400) // HTTP状态码(可选)
);

// 在API响应中返回错误
return rest_ensure_response($error);

若要在购物车更新的API流程中注入错误,可使用woocommerce_rest_cart_update_items_errors过滤器:

add_filter('woocommerce_rest_cart_update_items_errors', 'custom_rest_cart_errors', 10, 2);
function custom_rest_cart_errors($errors, $request) {
    $errors[] = new WP_Error(
        'custom_api_error',
        '自定义API错误提示',
        array('status' => 400)
    );
    return $errors;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 15:13:32