# Plugin API

URL: https://rustpress.witsberry.com/plugin-api/

> Reference for RustPress plugins: meta boxes, roles, rewrite rules, blocks, WP_Query, $wpdb, HTTP calls, private files, hooks and plugin dependencies.

This page is the reference for what a plugin can do. Start with [Plugins](/plugins/) for runtimes and a first plugin. Everything here works in all four SDKs (JavaScript, PHP, Python and Rust), sent over the same JSON protocol. Each plugin is described once (`describe`), then called only for what it registered. In JavaScript, `const rp = require('rustpress')()` gives the SDK object; the examples call it `rp` or `wp`, which are the same thing.

## The manifest

```
{
  "name": "My Plugin",
  "version": "1.0.0",
  "runtime": "js",
  "entry": "plugin.js",
  "permissions": ["content:read"],
  "network": ["api.stripe.com"],
  "requires": ["shop-core (>=1.2)"],
  "requires_rustpress": "0.1.4",
  "scope": { "areas": ["front"], "paths": ["/shop/*"], "post_types": ["product"] }
}
```

*   `runtime`: `js`, `wasm`, `stdio` or `http`. A folder with a classic PHP file (a `Plugin Name:` header) needs no manifest.
*   `stdio` runs `entry` by extension (`.php`, `.js`, `.py`, `.rb`) or a `"command"`. `http` takes a `"url"` or a `"serve"` command the core starts with `{port}` / `$PORT`.
*   `scope` limits where filters and actions run: `areas` (front, admin, rest), `paths`, `exclude_paths`, `post_types`, `pages` (front\_page, home, single, page, archive, search, 404). In PHP: `Load On: front, admin` and `Load On Paths: /shop/*`. Shortcodes, blocks, routes, admin pages and scheduled events aren’t limited.
*   Sandboxed JavaScript can only require the SDK. It has no `fetch`, timers, files or `process`. Each call starts fresh with a time budget and 64 MB of memory, so keep data in options or tables.

## Dependencies between plugins

Declare hard needs in `plugin.json`, or in a PHP header and a theme’s `style.css`:

```
Requires Plugins: shop-core, payments (>=1.2)
Requires RustPress: 0.1.4
```

*   A package isn’t activated until every plugin it requires is installed, active and at least that version, and the site runs that RustPress.
*   A required plugin can’t be deactivated or deleted while something active needs it. The Plugins screen says which.
*   Versions are written `(>=1.2)`, `>=1.2`, `(>=v2)` or `(>=1.2-beta)`. Ranges and other operators aren’t supported, and a requirement RustPress can’t read keeps the package off.
*   Anything optional is an integration you check for with `isPluginActive(slug)` / `is_plugin_active()`. Packages talk through hooks and REST routes, never by reading each other’s tables, options or files.

## Hooks between plugins

A plugin’s public extension points are hooks it fires, named with its slug. Firing one runs its own callbacks, then every other package’s:

| SDK        | Fire an action                                       | Filter a value                                                | Is a plugin there?                    |
| ---------- | ---------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------- |
| PHP        | `do_action( 'shop_core_order_paid', $id )`           | `apply_filters( 'shop_core_cart_total', $t, $cart )`          | `is_plugin_active( 'shop-core' )`     |
| JavaScript | `await rp.doAction('shop_core_order_paid', id)`      | `await rp.applyFilters('shop_core_cart_total', t, cart)`      | `rp.isPluginActive('shop-core')`      |
| Python     | `do_action("shop_core_order_paid", id)`              | `apply_filters("shop_core_cart_total", t, cart)`              | `is_plugin_active("shop-core")`       |
| Rust       | `do_action("shop_core_order_paid", vec![json!(id)])` | `apply_filters("shop_core_cart_total", json!(t), vec![cart])` | `is_plugin_active(&req, "shop-core")` |

*   A plugin may fire its own hooks, those of plugins it lists in `requires`, and shared WordPress-style hooks no plugin owns (such as `the_content`).
*   It may never fire core lifecycle actions (`init`, `wp_head`, `save_post`…), hooks starting with `rp_`, or scheduled events’ hooks.
*   Listeners run as the visitor, never as an administrator, and see who fired the hook in `context.fired_by`.
*   Document every hook you fire in your `AGENTS.md`: it is your plugin’s API.

## Custom fields and meta boxes

Describe `meta_boxes` and RustPress draws the fields on the post editor, checks every value and saves it as post meta. A wrong value stops the save and tells the editor what to fix.

```
rp.addMetaBox('product_details', {
  title: 'Product details', postTypes: ['product'], context: 'side',
  fields: [
    { key: 'price', label: 'Price', type: 'number', min: 0, step: 0.01, required: true },
    { key: 'colour', label: 'Colour', type: 'select', options: ['red', 'blue'] },
    { key: 'gallery', label: 'Gallery', type: 'repeater', fields: [{ key: 'image', type: 'image' }] }
  ]
});
```

*   Field types: `text`, `textarea`, `html`, `number`, `url`, `email`, `date`, `time`, `datetime`, `color`, `checkbox`, `select`, `radio`, `image`, `file`, `post`, `user`, `repeater`.
*   Drawn boxes (pass a `render(post)` callback) return their own HTML (form controls allowed, no scripts) and save in `save_post`.
*   Boxes can also target user profiles (`object: 'user'`) or terms (`object: 'term'` with `taxonomies`).
*   Read and write with `rp.getPostMeta / updatePostMeta / deletePostMeta`, or `get_post_meta`, `update_post_meta`, `register_post_meta` and `add_meta_box` in PHP. Keys named after the plugin need no permission.

## Roles and capabilities

With the `users` permission a plugin can `add_role`, `remove_role` (only roles it added), `add_cap`, `remove_cap`, `set_user_role` (never to or from administrator) and check `user_can`. Granting site-wide capabilities such as `manage_options` also needs `site`. A post type with `"capability_type": "book"` gets `edit_books`, `publish_books` and the rest.

## Rewrite rules and query variables

```
"rewrite_rules": [{ "regex": "^events/([0-9]{4})/?$",
  "query": "index.php?post_type=event&event_year=$matches[1]", "after": "top" }],
"query_vars": ["event_year"]
```

Top rules run before the core’s addresses, bottom ones only when nothing else matched. Core addresses can’t be rewritten. The plugin’s variables arrive in `context.query.vars`; pick a template with the `template_include` filter.

## Templates for your content types

A plugin that registers a content type or taxonomy can ship `templates/single-<type>.html`, `archive-<type>.html` or `taxonomy-<taxonomy>.html`. They are used when the active theme has no file of that name, and wrap the theme’s layout:

```
{% extends layout %}
{% block main %}<article><h1>{{ post.title }}</h1>{{ post.content|safe }}</article>{% endblock %}
```

## Editor blocks

Describe `block_types` with WordPress-style `attributes`. The editor offers the block under “From plugins”, shows the attributes as a settings form with a live preview, and saves only values that differ from the default. Every view renders it with a `block` call; attributes arrive typed, with values that don’t fit replaced by the default. For your own editing UI, register an editor script and call `rpBlocks.registerEdit(name, (el, ctx) => { … })`.

## Scripts and styles

Describe `assets` (handle, src, type, deps, strategy, where: front, admin, login or editor), or enqueue them in `wp_enqueue_scripts` as in WordPress. Each handle is printed once, dependencies first. Files in the plugin get content-hashed names cached for a year, so `version` doesn’t need bumping.

## Admin pages, settings and widgets

*   Admin pages can be a menu of their own (`top_level`, `position`), sit under a core menu (`parent`), or be full screen for page builders.
*   An admin page with `sections` of fields is drawn, checked and saved by the core, with no HTML to write. `rp_settings_saved` fires after a save.
*   Dashboard widgets (`dashboard_widgets`) can be hidden and moved by each user. Sidebar widgets are blocks.
*   Every admin screen has the media dialog: `await rpMedia.open({ type: 'image' })`, or WordPress’s `wp.media()`.

## Querying content

`query_posts` takes `WP_Query` arguments, including `meta_query` (nested AND/OR, all compare operators and types), `tax_query`, ordering by meta value and paging up to 1000 per page. Published content of public types needs no permission.

Ported code can use `$wpdb` and `dbDelta` in PHP. The core parses each statement and allows `CREATE TABLE` for the plugin’s own tables, reads and writes on its own tables, and reads on posts, terms and comments with `content:read`. Users, options, passwords and commenters’ emails and IPs are never reachable. Every value is bound as a parameter.

## Plugin tables

```
await rp.db.createTable('orders', { status: 'string', total: 'float', data: 'json' }, ['status']);
const { id } = await rp.db.insert('orders', { status: 'paid', total: 12.5 });
const { rows } = await rp.db.select('orders', { status: 'paid', total: { '>=': 10 } },
  { orderBy: 'id', order: 'desc', limit: 20 });
```

Types are `int`, `float`, `bool`, `string`, `text`, `datetime` and `json`; `id` is added as the key. Conditions use `=`, `!=`, `<`, `<=`, `>`, `>=`, `like` and `in`. Up to 32 tables and 64 columns, 1000 rows per select. In PHP: `rp_db_create_table`, `rp_db_insert`, `rp_db_select` and friends. When a plugin is removed, the owner can delete its tables with it.

## Calling other websites

The `http` host call needs the `network` permission; `"network": ["api.stripe.com", "*.paypal.com"]` (PHP header `Network:`) limits it to those hosts. Only public addresses are reached, never this server or private and cloud-metadata addresses, even after redirects. Calls take at most 15 seconds and 5 MB. SDKs: `rp.http(method, url, { headers, body })`, `wp_remote_get/post/request` and `rp_http()` in PHP, `http()` in Python.

## Private files

Invoices, downloads and exports go in `rp-content/plugin-files/<slug>/`, which is never served directly: `rp.files.put/get/delete/exists/list`, `rp_file_put()` and friends. To hand one to a visitor after your own checks, a page or route answers:

```
{ "file": "invoices/42.pdf", "download_name": "Invoice 42.pdf" }
```

Files can be up to 50 MB each and 2 GB per plugin. Bytes a plugin makes, such as a QR code or a chart, go back as `body_base64` with a `Content-Type`.

## Requests, cookies, nonces and CSRF

*   `context.request` carries the method, path, query, IP, user agent and only the plugin’s own cookies (`rp_<slug>__<name>`). The login cookie and other plugins’ cookies are never shown.
*   `set_cookie` and `redirect` host calls change the response. Pages for visitors with `rp_` cookies are never shared by the page cache.
*   `nonce_create` / `nonce_verify` are made for the user and session, and namespaced to the plugin.
*   Changing requests that carry cookies must come from this site or carry a CSRF token from `GET /rp-csrf`, otherwise they get 419. Webhooks and application passwords (no cookies) pass.

## AI tools

Plugins can give the site’s agents and MCP clients their own tools with `rp.registerAiTool()` or `rp_register_ai_tool()`. See [MCP and AI tools](/mcp-and-ai-tools/).

## SEO, cache and media storage hooks

*   **SEO:** `rp_schema_graph` adds JSON-LD nodes (Product, Event, FAQPage…), `rp_seo_output` turns the core’s tags off for an SEO plugin, `rp_llms_txt`, `rp_ai_readable` and `rp_llms_posts` shape what AI tools can read.
*   **Page cache:** `rp_page_cacheable`, `rp_page_cache_key`, `rp_page_cache_ttl`, and the `rp_cache_purged` action for purging a CDN.
*   **Media storage (S3, R2, a CDN):** copy files in `add_attachment`, remove them in `delete_attachment`, then set the `rp_media_url_base` option. Storage plugins run as PHP, Node or Python, not in the sandbox.

## Hooks you can use

Filters and actions keep WordPress’s names and arguments where they exist: request hooks (`init`, `template_redirect`, `template_include`, `wp_headers`), queries and links (`pre_get_posts`, `post_link`), output (`wp_head`, `the_content`, `body_class`, `render_block`), posts and data (`save_post`, `transition_post_status`), comments (`preprocess_comment`), users and login (`authenticate` for a second factor, `wp_login`), media (`wp_handle_upload_prefilter`), settings (`update_option_{name}`), REST (`rest_prepare_{type}`) and admin (`admin_notices`, `admin_bar_menu`). Plugins can’t rewrite other routes’ API responses, so one plugin can never change what the admin sees, approvals included.

The complete list of operations, fields and limits is in [PROTOCOL.md](https://github.com/Witsberry/RustPress/blob/main/bundled/sdk/PROTOCOL.md) on GitHub, which is also written to `sdk/PROTOCOL.md` beside every site’s `rp-config.toml`.
