多くの WordPress プラグインは EmDash に移植できます。モデルは異なります—PHP ではなく TypeScript、actions/filters ではなく hooks、wp_options ではなく構造化ストレージ—ですが、機能の多くはきれいに対応付けられます。
移植の見極め
すべてのプラグインが移植に向いているわけではありません。着手前に候補を評価してください。
向いているもの
カスタムフィールド、SEO、コンテンツ処理、管理 UI 拡張、アナリティクス、SNS、フォーム
向かないもの
マルチサイト機能、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 はプラグイン定義で型付きフックを宣言します。
ライフサイクル
| 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"); カスタムテーブル → ストレージコレクション
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 プラグインを分析
フック、DB アクセス、管理ページ、REST エンドポイントを整理する。
-
EmDash の概念に対応付ける
WordPress フック → EmDash フック。
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: {}, }); } -
実装順序
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
セキュリティサンドボックスのため、必要な 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 を使わない — 構造化されたストレージコレクションを使う。
ファイルシステムに頼らない — ファイルはメディア API を使う。
次のステップ
- Hooks Reference — シグネチャ付きの全フック
- Storage API — コレクションとクエリ
- Settings — 設定スキーマと KV
- Admin UI — 管理画面の構築