許多 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 — 建立後台頁面