Molti plugin WordPress si possono portare su EmDash. Il modello è diverso—TypeScript al posto di PHP, hook al posto di action/filter, storage strutturato al posto di wp_options—ma gran parte della logica si mappa in modo chiaro.
Valutazione di portabilità
Non tutti i plugin vanno portati. Valuta i candidati prima di iniziare.
Buoni candidati
Campi personalizzati, SEO, processori di contenuto, estensioni UI admin, analytics, social, moduli
Scarsi candidati
Multisite, integrazioni WooCommerce/Gutenberg, plugin che patchano il core di WordPress
Confronto di struttura
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 Mappatura degli hook
WordPress usa add_action() e add_filter() con nomi stringa. EmDash usa hook tipizzati nella definizione del plugin.
Hook del ciclo di vita
| WordPress | EmDash | Note |
|---|---|---|
register_activation_hook() | plugin:install | Una volta alla prima installazione |
| Plugin abilitato | plugin:activate | All’attivazione |
| Plugin disabilitato | plugin:deactivate | Alla disattivazione |
register_uninstall_hook() | plugin:uninstall | event.deleteData = scelta utente |
Hook sui contenuti
| WordPress | EmDash | Note |
|---|---|---|
wp_insert_post_data | content:beforeSave | Restituire contenuto modificato o lanciare per annullare |
save_post | content:afterSave | Effetti dopo il salvataggio |
before_delete_post | content:beforeDelete | Restituire false per annullare |
deleted_post | content:afterDelete | Pulizia dopo eliminazione |
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);
}
},
} Hook sui media
| WordPress | EmDash | Note |
|---|---|---|
wp_handle_upload_prefilter | media:beforeUpload | Validare o trasformare |
add_attachment | media:afterUpload | Dopo il caricamento |
Mappatura dello storage
API Options → archivio 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"); Tabelle personalizzate → collection di 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,
}); Schema impostazioni
WordPress usa la Settings API per i form admin. EmDash usa uno schema dichiarativo che genera l’UI automaticamente.
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 di amministrazione
Le pagine admin WordPress sono PHP. EmDash usa componenti 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>;
},
};
Registra nella definizione del plugin:
admin: {
entry: "@my-org/my-plugin/admin",
pages: [{ path: "/settings", label: "Dashboard" }],
widgets: [{ id: "summary", title: "Summary", size: "half" }],
},
REST API → route del plugin
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 };
},
},
}, Le route sono in /_emdash/api/plugins/{plugin-id}/{route-name}.
Processo di porting
-
Analizza il plugin WordPress
Documenta hook, accesso al database, pagine admin, endpoint REST.
-
Mappa su EmDash
Hook WordPress → hook EmDash.
wp_options→ctx.kv. Tabelle custom → collection storage. Pagine admin → React. REST → route plugin. -
Crea lo scheletro
import { definePlugin } from "emdash"; export function createPlugin() { return definePlugin({ id: "my-ported-plugin", version: "1.0.0", capabilities: [], storage: {}, hooks: {}, routes: {}, admin: {}, }); } -
Implementa in ordine
Storage → Hook → UI admin → Route
-
Testa a fondo
Verifica che gli hook si attivino, lo storage funzioni e l’UI si renderizzi.
Esempio: plugin tempo di lettura
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
I plugin devono dichiarare le capabilities per la sandbox di sicurezza:
| Capability | Fornisce | Caso d’uso |
|---|---|---|
network:fetch | ctx.http.fetch() | Chiamate API esterne |
read:content | ctx.content.get(), list() | Leggere contenuti CMS |
write:content | ctx.content.create(), ecc. | Modificare contenuti |
read:media | ctx.media.get(), list() | Leggere media |
write:media | ctx.media.getUploadUrl() | Caricare media |
Errori comuni
Niente stato globale — Usa lo storage invece delle variabili globali.
Tutto asincrono — Usa sempre await per storage e API.
Niente SQL diretto — Usa collection di storage strutturate.
Niente file system — Usa l’API media per i file.
Passi successivi
- Hooks Reference — Tutti gli hook con firme
- Storage API — Collection e query
- Settings — Schema impostazioni e KV
- Admin UI — Pagine di amministrazione