WooCommerce中woocommerce_order_status_changed触发时admin_notices不生效问题
问题根因
你写的代码无法触发通知是因为woocommerce_order_status_changed钩子的触发时机晚于后台页面admin_notices钩子的执行阶段,当订单状态变更触发回调时,页面通知的渲染逻辑已经执行完毕,此时再挂载admin_notices回调不会生效。同时订单状态变更操作完成后会触发页面重定向,挂载的钩子会在重定向后丢失,自然无法显示。
解决方案
通过WordPress的transient机制存储临时通知标识,重定向后判断标识存在就输出对应通知,用完即删即可,完整实现代码如下:
<?php class TestNotice { // 通知标识的唯一键名 private $notice_key = 'wc_order_status_change_notice'; public function testTheNotice() { // 监听订单状态变更钩子 add_action('woocommerce_order_status_changed', [$this, 'handle_order_status_change'], 10, 4); // 全局挂载admin通知输出钩子 add_action('admin_notices', [$this, 'output_notice']); } public function handle_order_status_change(int $id, string $statusFrom, string $statusTo, WC_Order $order) { // 存储临时通知,有效期30秒,避免过期残留 set_transient($this->notice_key, true, 30); } public function output_notice() { // 仅在WooCommerce订单相关后台页面显示 $screen = get_current_screen(); if ($screen->id !== 'edit-shop_order' && $screen->id !== 'shop_order') { return; } // 判断是否需要显示通知 if (get_transient($this->notice_key)) { // 输出红色边框的错误类通知 ?> <div class="notice notice-error is-dismissible"> <p>This notice appears on the order page.</p> </div> <?php // 用完就删除临时标识,避免重复显示 delete_transient($this->notice_key); } } } $testNotice = new TestNotice(); $testNotice->testTheNotice();
代码说明
- 通知的展示逻辑通过全局挂载的
admin_notices钩子实现,不会出现触发时机错位的问题 - 仅在订单列表页、订单详情页展示通知,不会出现在其他后台页面
- 直接使用
notice-error类即可实现红色边框的错误通知,不需要调用WC_Admin_Notices类,自定义更灵活 - 临时标识设置了30秒有效期,就算用户没触发页面加载也不会长期残留
内容的提问来源于stack exchange,提问作者Chloé
相关产品推荐
相关产品推荐

