许多 WordPress 插件可以移植到 EmDash。插件模型不同——用 TypeScript 替代 PHP,用 hooks 替代 actions/filters,用结构化存储替代 wp_options——但大多数功能都能清晰对应。
是否值得移植
并非所有插件都值得移植。开始前先评估候选插件。
适合移植
自定义字段、SEO、内容处理、后台 UI 扩展、分析、社交分享、表单
不适合移植
多站点功能、WooCommerce/Gutenberg 深度集成、修改 WordPress 核心的插件
插件结构对比
WordPress
wp-content/plugins/my-plugin/
├── my-plugin.php # Main file with plugin header
├── includes/
│ ├── class-admin.php
│ └── class-api.php
└── admin/
└── js/ EmDash
my-plugin/
├── src/
│ ├── index.ts # Plugin definition (definePlugin)
│ └── admin.tsx # Admin UI exports (React)
├── package.json
└── tsconfig.json 钩子对应关系
WordPress 使用 add_action() 和 add_filter() 配合字符串钩子名。EmDash 在插件定义中声明类型化的 hooks。
生命周期钩子
| WordPress | EmDash | 说明 |
|---|---|---|
register_activation_hook() | plugin:install | 首次安装时执行一次 |
| 插件启用 | plugin:activate | 启用时 |
| 插件禁用 | plugin:deactivate | 禁用时 |
register_uninstall_hook() | plugin:uninstall | event.deleteData 表示用户是否删除数据 |
内容钩子
| 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);
}
},
} 媒体钩子
| WordPress | EmDash | 说明 |
|---|---|---|
wp_handle_upload_prefilter | media:beforeUpload | 校验或转换上传 |
add_attachment | media:afterUpload | 上传完成后 |
存储对应关系
Options API → KV 存储
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"); 自定义表 → Storage 集合
WordPress
global $wpdb;
$table = $wpdb->prefix . 'my_plugin_items';
// Insert
$wpdb->insert($table, ['name' => 'Item 1', 'status' => 'active']);
// Query
$items = $wpdb->get_results(
"SELECT \* FROM $table WHERE status = 'active' LIMIT 10"
);
EmDash
// Declare in plugin definition
storage: {
items: {
indexes: ["status", "createdAt"],
},
},
// In hooks or 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,
}); 设置架构
WordPress 用 Settings API 构建后台表单。EmDash 使用声明式架构并自动生成 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 Key",
description: "Your API key from the dashboard",
},
enabled: {
type: "boolean",
label: "Enabled",
default: true,
},
limit: {
type: "number",
label: "Item Limit",
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>Total items: {count}</div>;
},
};
export const pages = {
settings: function SettingsPage() {
// React component for settings page
return <div>Settings content</div>;
},
};
在插件定义中注册:
admin: {
entry: "@my-org/my-plugin/admin",
pages: [{ path: "/settings", label: "Dashboard" }],
widgets: [{ id: "summary", title: "Summary", 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 插件
记录钩子、数据库操作、后台页面、REST 端点。
-
映射到 EmDash 概念
WordPress 钩子 → EmDash 钩子。
wp_options→ctx.kv。自定义表 → Storage 集合。后台页 → React。REST → 插件路由。 -
搭建插件骨架
import { definePlugin } from "emdash"; export function createPlugin() { return definePlugin({ id: "my-ported-plugin", version: "1.0.0", capabilities: [], storage: {}, hooks: {}, routes: {}, admin: {}, }); } -
建议实现顺序
Storage → 钩子 → 后台 UI → 路由
-
充分测试
确认钩子触发、存储可用、后台 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: "Words per minute",
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 };
},
},
});
} Capabilities
插件须声明沙箱所需能力:
| Capability | 提供 | 用途 |
|---|---|---|
network:fetch | ctx.http.fetch() | 调用外部 API |
read:content | ctx.content.get(), list() | 读取 CMS 内容 |
write:content | ctx.content.create() 等 | 修改内容 |
read:media | ctx.media.get(), list() | 读取媒体 |
write:media | ctx.media.getUploadUrl() | 上传媒体 |
常见陷阱
避免全局状态 — 用 storage 代替全局变量。
全面异步 — 对 storage 和 API 调用始终 await。
不要直接写 SQL — 使用结构化 storage 集合。
不要碰文件系统 — 文件请走媒体 API。
下一步
- Hooks Reference — 全部钩子及签名
- Storage API — 集合与查询
- Settings — 设置架构与 KV
- Admin UI — 构建后台页面