许多 WordPress 插件可以移植到 EmDash。插件模型有所不同——TypeScript 而非 PHP,hooks 而非 actions/filters,结构化存储而非 wp_options——但大多数功能都能完美映射。
可移植性评估
并非所有插件都适合移植。在开始前评估候选插件。
适合的候选插件
自定义字段、SEO 插件、内容处理器、管理 UI 扩展、分析、社交分享、表单
不适合的候选插件
多站点功能、WooCommerce/Gutenberg 集成、修补 WordPress 核心内部的插件
插件结构对比
WordPress
wp-content/plugins/my-plugin/
├── my-plugin.php # 带有插件头的主文件
├── includes/
│ ├── class-admin.php
│ └── class-api.php
└── admin/
└── js/ EmDash
my-plugin/
├── src/
│ ├── index.ts # 插件定义 (definePlugin)
│ └── admin.tsx # 管理 UI 导出 (React)
├── package.json
└── tsconfig.json Hooks 映射
WordPress 使用带字符串 hook 名称的 add_action() 和 add_filter()。EmDash 使用在插件定义中声明的类型化 hooks。
生命周期 Hooks
| WordPress | EmDash | 备注 |
|---|---|---|
register_activation_hook() | plugin:install | 首次安装时运行一次 |
| 插件启用 | plugin:activate | 启用时运行 |
| 插件禁用 | plugin:deactivate | 禁用时运行 |
register_uninstall_hook() | plugin:uninstall | event.deleteData 表示用户的选择 |
内容 Hooks
| WordPress | EmDash | 备注 |
|---|---|---|
wp_insert_post_data | content:beforeSave | 返回修改的内容或抛出错误以取消 |
save_post | content:afterSave | 保存后的副作用 |
before_delete_post | content:beforeDelete | 返回 false 以取消 |
deleted_post | content:afterDelete | 删除后的清理 |
WordPress
add_action('save_post', function($post_id, $post, $update) {
if ($post->post_type !== 'product') return;
$price = get_post_meta($post_id, 'price', true);
if ($price > 1000) {
update_post_meta($post_id, 'is_premium', true);
}
}, 10, 3);
EmDash
hooks: {
"content:afterSave": async (event, ctx) => {
if (event.collection !== "products") return;
const price = event.content.price as number;
if (price > 1000) {
await ctx.kv.set(`premium:${event.content.id}`, true);
}
},
} 媒体 Hooks
| WordPress | EmDash | 备注 |
|---|---|---|
wp_handle_upload_prefilter | media:beforeUpload | 验证或转换 |
add_attachment | media:afterUpload | 上传后响应 |
存储映射
Options API → KV Store
WordPress
$api_key = get_option('my_plugin_api_key', '');
update_option('my_plugin_api_key', 'abc123');
delete_option('my_plugin_api_key'); EmDash
const apiKey = await ctx.kv.get<string>("settings:apiKey") ?? "";
await ctx.kv.set("settings:apiKey", "abc123");
await ctx.kv.delete("settings:apiKey"); 自定义表 → 存储集合
WordPress
global $wpdb;
$table = $wpdb->prefix . 'my_plugin_items';
// 插入
$wpdb->insert($table, ['name' => 'Item 1', 'status' => 'active']);
// 查询
$items = $wpdb->get_results(
"SELECT \* FROM $table WHERE status = 'active' LIMIT 10"
);
EmDash
// 在插件定义中声明
storage: {
items: {
indexes: ["status", "createdAt"],
},
},
// 在 hooks 或 routes 中:
await ctx.storage.items.put("item-1", {
name: "Item 1",
status: "active",
createdAt: new Date().toISOString(),
});
const result = await ctx.storage.items.query({
where: { status: "active" },
limit: 10,
}); 设置 Schema
WordPress 使用 Settings API 处理管理表单。EmDash 使用声明式 schema 自动生成 UI。
WordPress
add_action('admin_init', function() {
register_setting('my_plugin', 'my_plugin_api_key');
add_settings_section('main', 'Settings', null, 'my-plugin');
add_settings_field('api_key', 'API Key', function() {
$value = get_option('my_plugin_api_key');
echo '<input type="text" name="my_plugin_api_key"
value="' . esc_attr($value) . '">';
}, 'my-plugin', 'main');
}); EmDash
admin: {
settingsSchema: {
apiKey: {
type: "secret",
label: "API 密钥",
description: "来自仪表板的 API 密钥",
},
enabled: {
type: "boolean",
label: "已启用",
default: true,
},
limit: {
type: "number",
label: "项目限制",
default: 100,
min: 1,
max: 1000,
},
},
} 管理 UI
WordPress 管理页面是 PHP。EmDash 使用 React 组件。
import { useState, useEffect } from "react";
export const widgets = {
summary: function SummaryWidget() {
const [count, setCount] = useState(0);
useEffect(() => {
fetch("/_emdash/api/plugins/my-plugin/status")
.then((r) => r.json())
.then((data) => setCount(data.count));
}, []);
return <div>总项目数: {count}</div>;
},
};
export const pages = {
settings: function SettingsPage() {
// 设置页面的 React 组件
return <div>设置内容</div>;
},
};
在插件定义中注册:
admin: {
entry: "@my-org/my-plugin/admin",
pages: [{ path: "/settings", label: "仪表板" }],
widgets: [{ id: "summary", title: "摘要", size: "half" }],
},
REST API → 插件路由
WordPress
register_rest_route('my-plugin/v1', '/items', [
'methods' => 'GET',
'callback' => function($request) {
global $wpdb;
$items = $wpdb->get_results("SELECT * FROM items LIMIT 50");
return new WP_REST_Response($items);
},
]); EmDash
routes: {
items: {
handler: async (ctx) => {
const result = await ctx.storage.items.query({ limit: 50 });
return { items: result.items };
},
},
}, 路由可在 /_emdash/api/plugins/{plugin-id}/{route-name} 访问。
移植流程
-
分析 WordPress 插件
记录它的功能:hooks、数据库操作、管理页面、REST 端点。
-
映射到 EmDash 概念
WordPress hooks → EmDash hooks。
wp_options→ctx.kv。自定义表 → 存储集合。管理页面 → React 组件。REST 端点 → 插件路由。 -
创建插件骨架
import { definePlugin } from "emdash"; export function createPlugin() { return definePlugin({ id: "my-ported-plugin", version: "1.0.0", capabilities: [], storage: {}, hooks: {}, routes: {}, admin: {}, }); } -
按顺序实现
存储 → Hooks → 管理 UI → 路由
-
彻底测试
验证 hooks 是否正确触发,存储是否工作,以及管理 UI 是否渲染。
示例:阅读时间插件
WordPress
add_filter('wp_insert_post_data', function($data, $postarr) {
if ($data['post_type'] !== 'post') return $data;
$content = strip_tags($data['post_content']);
$word_count = str_word_count($content);
$read_time = ceil($word_count / 200);
if (!empty($postarr['ID'])) {
update_post_meta($postarr['ID'], '_read_time', $read_time);
}
return $data;
}, 10, 2);
EmDash
export function createPlugin() {
return definePlugin({
id: "read-time",
version: "1.0.0",
admin: {
settingsSchema: {
wordsPerMinute: {
type: "number",
label: "每分钟字数",
default: 200,
min: 100,
max: 400,
},
},
},
hooks: {
"content:beforeSave": async (event, ctx) => {
if (event.collection !== "posts") return;
const wpm = await ctx.kv.get<number>("settings:wordsPerMinute") ?? 200;
const text = JSON.stringify(event.content.body || "");
const readTime = Math.ceil(text.split(/\s+/).length / wpm);
return { ...event.content, readTime };
},
},
});
} 权限
插件必须声明安全沙箱所需的权限:
| 权限 | 提供 | 用例 |
|---|---|---|
network:request | ctx.http.fetch() | 外部 API 调用 |
content:read | ctx.content.get(), list() | 读取 CMS 内容 |
content:write | ctx.content.create(), etc. | 修改内容 |
media:read | ctx.media.get(), list() | 读取媒体 |
media:write | ctx.media.getUploadUrl() | 上传媒体 |
常见陷阱
无全局状态 — 使用存储而非全局变量。
一切异步 — 始终对存储和 API 调用使用 await。
无直接 SQL — 使用结构化存储集合。
无文件系统 — 使用媒体 API 处理文件。
后续步骤
- Hooks — 所有带签名的 hooks
- Storage — 集合和查询
- Settings — 通过 Block Kit 支持的 KV 设置
- React Admin Pages & Widgets — 构建管理页面(原生插件)