WordPress Gutenberg中文章更新时如何向编辑器发送无刷新通知
在Gutenberg编辑器中实现文章更新后的无刷新通知
要在Gutenberg无刷新更新文章后显示API同步的通知,需要后端传递同步状态+前端监听响应并触发通知,具体实现如下:
1. 后端:记录API同步结果并注入REST响应
首先在post_updated钩子完成API对接后,把同步结果临时存储,再通过REST响应钩子把结果传递给前端:
// 处理API对接并存储同步结果 add_action('post_updated', function($post_id, $post_after, $post_before) { // 你的外部API对接逻辑 $api_request = wp_remote_post('https://你的API地址', [ 'body' => [ 'post_id' => $post_id, 'post_title' => $post_after->post_title // 其他需要传递的参数 ] ]); // 判断同步是否成功 $sync_success = !is_wp_error($api_request) && wp_remote_retrieve_response_code($api_request) === 200; $sync_message = $sync_success ? '外部API同步成功' : '外部API同步失败,请检查接口配置'; // 将结果临时存储到文章元数据(用完即删) update_post_meta($post_id, '_temp_api_sync_result', [ 'success' => $sync_success, 'message' => $sync_message ]); }, 10, 3); // 在文章更新的REST响应中注入同步结果 add_filter('rest_pre_echo_response', function($response, $result, $request) { // 仅处理文章更新的PUT请求 if (preg_match('/^\/wp\/v2\/posts\/(\d+)$/', $request->get_route(), $matches) && $request->get_method() === 'PUT') { $post_id = $matches[1]; $sync_result = get_post_meta($post_id, '_temp_api_sync_result', true); if ($sync_result) { // 向响应添加自定义字段 $response['api_sync_result'] = $sync_result; // 删除临时存储的元数据,避免残留 delete_post_meta($post_id, '_temp_api_sync_result'); } } return $response; }, 10, 3);
2. 前端:拦截REST响应并显示Gutenberg通知
通过Gutenberg的API Fetch中间件拦截文章更新的响应,提取同步结果后用官方通知组件显示:
首先在主题目录下创建js/api-sync-notice.js文件,写入以下代码:
// 拦截REST API请求响应 wp.apiFetch.use((options, next) => { return next(options).then((response) => { // 判断是否为文章更新的响应且包含同步结果 if (options.path.match(/^\/wp\/v2\/posts\/\d+$/) && options.method === 'PUT' && response.api_sync_result) { const { success, message } = response.api_sync_result; // 使用Gutenberg内置通知组件显示消息 wp.notifications.createNotice( success ? 'success' : 'error', message, { isDismissible: true } ); } return response; }); });
然后在主题的functions.php中加载这个JS文件到编辑器:
// 加载编辑器端的通知脚本 add_action('enqueue_block_editor_assets', function() { wp_enqueue_script( 'api-sync-notification', get_template_directory_uri() . '/js/api-sync-notice.js', ['wp-api-fetch', 'wp-notifications', 'wp-editor'], // 依赖Gutenberg核心脚本 wp_get_theme()->get('Version'), true // 在页脚加载 ); });
补充说明
- 这种方法完全适配Gutenberg的无刷新更新逻辑,不需要刷新页面就能实时显示通知
- 临时存储的文章元数据会在响应返回后立即删除,不会产生冗余数据
- 通知使用Gutenberg官方的
wp.notifications组件,样式与编辑器原生通知一致,保持体验统一
内容的提问来源于stack exchange,提问作者Dariel Corchado
相关产品推荐
相关产品推荐

