如何在不创建自定义块的情况下扩展Gutenberg core/link搜索结果?
实现方案(无需自定义块)
方案1:前端钩子修改搜索结果
利用Gutenberg内置的editor.URLSearchResults过滤器,在前端拦截搜索请求并追加第三方API返回的链接结果:
- 在主题
functions.php中注册前端脚本,确保在Gutenberg编辑器加载时注入:
function enqueue_custom_link_search_script() { if (is_admin()) { wp_enqueue_script( 'custom-link-search', get_template_directory_uri() . '/js/custom-link-search.js', array('wp-hooks', 'wp-editor', 'wp-api'), wp_get_theme()->get('Version'), true ); } } add_action('admin_enqueue_scripts', 'enqueue_custom_link_search_script');
- 在
js/custom-link-search.js中编写过滤器逻辑,处理API请求并合并结果:
wp.hooks.addFilter( 'editor.URLSearchResults', 'custom/extend-link-search', async (results, searchTerm) => { if (!searchTerm.trim()) return results; try { // 通过WP REST API代理请求第三方API(规避CORS问题) const proxyRes = await fetch('/wp-json/custom/v1/search-external-links', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': wpApiSettings.nonce }, body: JSON.stringify({ search: searchTerm }) }); const externalData = await proxyRes.json(); // 转换为Gutenberg搜索结果要求的格式 const formattedLinks = externalData.map(item => ({ url: item.url, title: item.title, type: 'external', subtype: 'third-party-link' })); return [...results, ...formattedLinks]; } catch (err) { console.error('加载外部链接失败:', err); return results; } } );
- 注册REST API代理端点(在
functions.php中):
add_action('rest_api_init', function() { register_rest_route( 'custom/v1', '/search-external-links', array( 'methods' => 'POST', 'callback' => 'fetch_external_links', 'permission_callback' => fn() => current_user_can('edit_posts') ) ); }); function fetch_external_links($request) { $searchTerm = $request->get_param('search'); if (empty($searchTerm)) return []; // 调用第三方API $apiUrl = 'https://第三方API地址?search=' . urlencode($searchTerm); $apiRes = wp_remote_get($apiUrl); if (is_wp_error($apiRes)) return []; $body = wp_remote_retrieve_body($apiRes); return json_decode($body, true) ?: []; }
方案2:修改REST API搜索响应
通过PHP过滤器修改Gutenberg默认调用的wp/v2/search端点返回结果,直接追加外部链接:
在functions.php中添加以下代码:
add_filter('rest_pre_echo_response', function($response, $result, $request) { // 仅处理链接搜索的REST请求 if ($request->get_route() !== '/wp/v2/search' || !isset($request['search'])) { return $response; } $searchTerm = $request['search']; // 缓存结果,减少API重复调用 $cacheKey = 'external_links_' . md5($searchTerm); $externalLinks = wp_cache_get($cacheKey); if (!$externalLinks) { $apiUrl = 'https://第三方API地址?search=' . urlencode($searchTerm); $apiRes = wp_remote_get($apiUrl); if (!is_wp_error($apiRes)) { $externalLinks = json_decode(wp_remote_retrieve_body($apiRes), true) ?: []; // 转换为WP搜索结果兼容格式 $externalLinks = array_map(function($item) { return [ 'id' => 'ext-' . uniqid(), 'title' => $item['title'], 'url' => $item['url'], 'type' => 'external', 'subtype' => 'custom' ]; }, $externalLinks); // 缓存1小时 wp_cache_set($cacheKey, $externalLinks, '', 3600); } else { $externalLinks = []; } } return array_merge($response, $externalLinks); }, 10, 3);
关键注意事项
- 跨域处理:优先通过PHP代理请求第三方API,避免前端直接调用时的CORS限制。
- 缓存优化:对第三方API请求结果做缓存,提升编辑器响应速度,减少不必要的API调用。
- 权限控制:仅允许具备编辑权限的用户触发外部链接搜索,避免恶意请求。
内容的提问来源于stack exchange,提问作者Sam Axe
相关产品推荐
相关产品推荐

