如何为块添加“继续写作”按钮?
解读
面试官抛出此题,核心想验证三件事:
- 你是否真正理解 Gutenberg 区块生命周期(从注册、编辑到保存)
- 能否在不破坏数据流的前提下,用 React 组件 + WordPress 数据层 优雅地扩展 UI
- 是否具备 国内落地经验——中文语料、本地化提示、国内大模型接口鉴权与合规
“继续写作”按钮本质是:在区块工具栏或检查器里插入一个自定义控件,点击后把已有内容作为 prompt,调用 国内大模型(通义千问、文心一言、讯飞星火等) 生成续写文本,再安全地回填到块属性并触发 undo 记录。整个流程必须走 WordPress REST 路由,前端用 @wordpress/api-fetch,后端用 register_rest_route,并做 权限校验与 内容过滤,防止 XSS 与 prompt 注入。
知识点
- Block Filter:
editor.BlockEdit与blocks.registerBlockType过滤器 - SlotFill:
BlockControls、InspectorControls、ToolbarButton - Data Layer:
useSelect读取块属性,useDispatch派发updateBlockAttributes - REST Controller:
register_rest_route+permission_callback+sanitize_callback - Nonce 与 Capability:
wp_create_nonce('wp_rest')与current_user_can('edit_posts') - 国内大模型鉴权:阿里云 AK/SK 签名、百度 OAuth、讯飞 APIKey,需走 服务端代理,禁止前端暴露密钥
- 性能与安全:
wp_kses_post过滤返回、设置 5 s 超时、记录WP_Error日志 - 国际化:
__()包裹文本,中文语言包zh_CN.mo随插件分发
答案
- 注册区块(或过滤核心段落块)
add_action('init', function(){
wp_register_script(
'continue-writing',
plugin_dir_url(__FILE__).'build/index.js',
['wp-blocks','wp-element','wp-data','wp-api-fetch'],
filemtime(__DIR__.'/build/index.js')
);
register_block_type('core/paragraph', [
'editor_script' => 'continue-writing',
]);
});
- 前端组件(build/index.js,基于
@wordpress/scripts打包)
import { addFilter } from '@wordpress/hooks';
import { BlockControls } from '@wordpress/block-editor';
import { ToolbarButton } from '@wordpress/components';
import { useSelect, useDispatch } from '@wordpress/data';
import apiFetch from '@wordpress/api-fetch';
const ContinueWriting = ({ clientId, attributes, setAttributes }) => {
const { content } = attributes;
const { updateBlockAttributes } = useDispatch('core/block-editor');
const onClick = async () => {
const res = await apiFetch({
path: '/continue-writing/v1/complete',
method: 'POST',
data: { prompt: content }
});
if (res && res.text) {
updateBlockAttributes(clientId, {
content: content + res.text
});
}
};
return (
<BlockControls>
<ToolbarButton
icon="controls-forward"
label="继续写作"
onClick={onClick}
/>
</BlockControls>
);
};
addFilter(
'editor.BlockEdit',
'continue-writing/add-button',
(Original) => (props) => (
<>
<Original {...props} />
<ContinueWriting {...props} />
</>
)
);
- 后端路由(插件主文件)
add_action('rest_api_init', function(){
register_rest_route('continue-writing/v1', '/complete', [
'methods' => 'POST',
'callback' => function($req){
$prompt = sanitize_text_field($req['prompt']);
if (empty($prompt)) return new WP_Error('empty', '内容为空', ['status'=>400]);
// 国内大模型代理请求,以通义千问为例
$ak = get_option('aliyun_ak');
$sk = get_option('aliyun_sk');
$body = wp_json_encode(['prompt'=>$prompt, 'max_tokens'=>150]);
$url = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation';
$response = wp_remote_post($url, [
'headers' => [
'Authorization' => 'Bearer ' . aliyun_sign($ak,$sk), // 自定义签名函数
'Content-Type' => 'application/json'
],
'body' => $body,
'timeout' => 5
]);
if (is_wp_error($response)) return $response;
$data = json_decode(wp_remote_retrieve_body($response), true);
$text = $data['output']['text'] ?? '';
return ['text' => wp_kses_post($text)];
},
'permission_callback' => function(){
return current_user_can('edit_posts');
}
]);
});
- 打包与部署
- 使用
@wordpress/scripts一键npm run build,生成build/index.js - 通过 Gitea + Jenkins 走 CI/CD,自动推送到国内云主机(阿里云 ECS、腾讯云 CVM)
- 启用
object-cache.php+ Redis 缓存 REST 响应,降低大模型调用费用
拓展思考
- 多语言续写:若站点为 中英文双语,可在 prompt 前加语言标记
"请用中文续写:",并读取用户locale判断 - 流式输出:国内大模型支持 SSE,可用
@wordpress/api-fetch+ReadableStream实现打字机效果,但需 polyfill 旧版 Safari - 费用控制:在服务端做 token 用量缓存,当日调用超过 1 万 token 时自动降级为本地 Markov 链 续写,并给编辑提示
- 合规审计:按《生成式 AI 服务管理暂行办法》要求,保存 6 个月 prompt 与生成日志,可在
wp_posts新建ai_log自定义文章类型,仅管理员可见 - 面试加分项:提到 WordPress 6.5 的 Block Bindings API,可把续写结果直接绑定到自定义字段,实现“一次生成、多处复用”,展示对 核心新特性 的跟进能力