Br resource cpt

From Lonsdale201/wp-agent-skills · View interactive version

Br resource cpt is an AI agent skill from the GitHub repository Lonsdale201/wp-agent-skills. Build better-route 1.1 CRUD endpoints over a WordPress custom post type with Resource::make, restNamespace, sourceCpt, allow, fields, filters, sort, filterSchema, writeSchema, policy, fieldPolicy, cptVisibleStatuses, cptVisibilityPolicy, pagination, deleteMode, uniformEnvelope, or a custom CPT repos

How to use this skill

Skill file

better-route: CPT Resource CRUD

Register the Resource itself during rest_api_init; it creates and registers its own internal Router from restNamespace.

use BetterRoute\Resource\Resource;
use BetterRoute\Resource\ResourcePolicy;

add_action('rest_api_init', static function (): void {
    Resource::make('books')
        ->restNamespace('myapp/v1')
        ->sourceCpt('book')
        ->allow(['list', 'get', 'create', 'update', 'delete'])
        ->fields(['id', 'title', 'slug', 'content', 'status', 'author'])
        ->filters(['status', 'author'])
        ->filterSchema([
            'status' => ['type' => 'enum', 'values' => ['publish', 'draft']],
            'author' => 'int',
        ])
        ->sort(['date', 'title', 'id'])
        ->policy(ResourcePolicy::publicReadPrivateWrite('edit_posts'))
        ->writeSchema([
            'title' => ['type' => 'string', 'required' => true, 'sanitize' => 'text'],
            'status' => ['type' => 'enum', 'values' => ['draft', 'publish']],
        ])
        ->deleteMode('trash')
        ->register();
});

Do not pass a Router to Resource::register(). Its optional argument is a DispatcherInterface, intended mainly for tests/custom dispatch.

Actions

Omitting allow() registers full CRUD. In 1.1:

Never configure both sourceCpt() and sourceTable(); the second call now throws.

CPT visibility

Default visible statuses are ['publish']. Configure the source-verified method:

->cptVisibleStatuses(['publish', 'draft'])

There is no allowedStatuses() method.

1.1 fails closed on reads:

Prefer an explicit Resource policy even though public CPT reads have a safe default.

For additional item logic:

->cptVisibilityPolicy(static function (array $item, string $action): bool {
    return ($item['tenant_id'] ?? null) === current_tenant_id();
})

The callback receives the projected repository item plus action (list or get), not just a status and not the WP request.

An arbitrary PHP callback cannot be pushed into WP_Query. To keep total, pages, and page contents truthful, 1.1 scans every matched repository page, applies the callback, then slices the visible set. This can be expensive. On large datasets, implement visibility in a custom query-level repository/filter so the database produces the correct total.

Query contract

List queries use:

Configure sort field names without a - prefix:

->sort(['date', 'title', 'id'])
// Client may request ?sort=-date

An empty sort configuration uses the defaults date and id; it is not an open/no-sort state. The repository adds ID as a stable tie-breaker.

Strict unknown-parameter checks allow WordPress globals _locale, _fields, _embed, _envelope, and _jsonp. This keeps wp.apiFetch's _locale=user compatible while rejecting other unknown input.

Configure pagination in any fluent order, but the final state must satisfy:

Exceeding maxPerPage or maxOffset returns 400 validation_failed; values are not silently clamped.

Writes and policies

Use flat enum rules:

['type' => 'enum', 'values' => ['draft', 'publish']]

Use br-write-schema for validation and br-resource-policy for action/field authorization. In 1.1 a denied fieldPolicy does not silently discard the field: it returns a validation error or 403 forbidden according to the rule type.

The default WordPressCptRepository also checks mapped CPT capabilities for create/update/delete and publishing/author changes. Resource route permission does not replace object-level WordPress capability checks.

Valid delete modes are force and trash.

Response and OpenAPI

Lists return {data, meta}. Create/update return {data}. A single get returns the raw item unless uniformEnvelope(true) is set; then it returns {data}.

After register(), call contracts() to export generated contracts. Provide <Resource>, <Resource>Input, <Resource>Response, and <Resource>ListResponse schemas in strict OpenAPI mode as applicable. Explicitly public Resource actions emit security: [].

PUT and PATCH now have distinct generated operation IDs (Update and Patch).

Regenerate clients that consumed duplicate IDs, validate the serialized document

and handle native WordPress validation errors as well as Better Route errors.

Review checklist

Related skills

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.