移植 WordPress 外掛

本頁內容

許多 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。

生命週期勾子

WordPressEmDash說明
register_activation_hook()plugin:install首次安裝時執行一次
外掛啟用plugin:activate啟用時
外掛停用plugin:deactivate停用時
register_uninstall_hook()plugin:uninstallevent.deleteData 表示使用者是否刪除資料

內容勾子

WordPressEmDash說明
wp_insert_post_datacontent:beforeSave回傳修改後的內容或拋錯以取消儲存
save_postcontent:afterSave儲存後的副作用
before_delete_postcontent:beforeDelete回傳 false 可取消刪除
deleted_postcontent: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);
        }
    },
}

媒體勾子

WordPressEmDash說明
wp_handle_upload_prefiltermedia:beforeUpload驗證或轉換上傳
add_attachmentmedia: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}

移植流程

  1. 分析 WordPress 外掛

    記錄勾子、資料庫操作、後台頁面、REST 端點。

  2. 對應到 EmDash 概念

    WordPress 勾子 → EmDash 勾子。wp_optionsctx.kv。自訂表 → Storage 集合。後台頁 → React。REST → 外掛路由。

  3. 建立外掛骨架

    import { definePlugin } from "emdash";
    
    export function createPlugin() {
    	return definePlugin({
    		id: "my-ported-plugin",
    		version: "1.0.0",
    		capabilities: [],
    		storage: {},
    		hooks: {},
    		routes: {},
    		admin: {},
    	});
    }
  4. 建議實作順序

    Storage → 勾子 → 後台 UI → 路由

  5. 充分測試

    確認勾子觸發、儲存可用、後台 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:fetchctx.http.fetch()呼叫外部 API
read:contentctx.content.get(), list()讀取 CMS 內容
write:contentctx.content.create()修改內容
read:mediactx.media.get(), list()讀取媒體
write:mediactx.media.getUploadUrl()上傳媒體

常見陷阱

避免全域狀態 — 以 storage 取代全域變數。

全面非同步 — 對 storage 與 API 呼叫一律 await

不要直接寫 SQL — 使用結構化 storage 集合。

不要碰檔案系統 — 檔案請走媒體 API。

下一步