Skip to content

Custom WordPress REST Endpoints for a Headless Frontend

Adityo Guni Waluyo

A dedicated REST surface for a headless frontend: app/v1 namespace, explicit permission_callback, publish-only resolver, and a best-effort transient throttle.

TL;DR

A headless WordPress backend needs custom REST endpoints for SEO meta, JSON-LD, view counts, and related posts. Key safety decisions: a versioned namespace, explicit permission callbacks, and one shared resolver exposing only published posts. Transient-based view throttling is best-effort, since transient expiration is a maximum, not a guarantee.

A WordPress backend serving a headless frontend does not stop at the default wp-json responses. The frontend needs per-post SEO meta, JSON-LD payloads, a view counter, and a list of related posts. Those four needs drove a dedicated REST surface in a headless WordPress project. The interesting lessons are a few small decisions that keep it safe.

A Numbered Namespace and Declared Permissions

Every custom route lives under one versioned namespace, for example app/v1. The rule is not a matter of taste: routes must be registered inside a rest_api_init callback so no work happens when the API is not in use, and WordPress core rejects an empty namespace with a message that routes must carry the plugin or theme name and its version [1][2].

The version number works as a contract with the frontend. If the shape of an endpoint's data changes fundamentally, a new versioned endpoint can be introduced without breaking clients that still live on the old one.

Another decision that is easy to skip: permission_callback. Since WordPress 5.5, registering a route without this argument triggers a _doing_it_wrong notice in the logs [1]. An endpoint that is genuinely public still declares it explicitly with __return_true. The difference is thin but real: the first is a documented decision, the second is a negligence that only surfaces through production logs.

The ground rules are clear. A permission callback that returns false stops the request before it is processed, and the WP_Error it returns is passed to the client as-is [1].

add_action( 'rest_api_init', function () {
    register_rest_route(
        'app/v1',
        '/post/(?P<post_id>\d+)/views',
        array(
            'methods'             => WP_REST_Server::READABLE,
            'permission_callback' => '__return_true',
            'args'                => array(
                'post_id' => array(
                    'type'              => 'integer',
                    'minimum'           => 1,
                    'required'          => true,
                    'validate_callback' => static fn( $p ) => is_numeric( $p ) && (int) $p > 0,
                ),
            ),
            'callback'            => 'app_handle_views',
        )
    );
} );

One Resolver, One Publish Guard

All four endpoints share a single resolver that maps a post ID to a post object. The resolver only returns posts with the publish status; anything else gets a WP_Error with the code rest_not_found and HTTP status 404. On a headless backend this guard is critical: a public frontend hits the API without context, and IDs can be guessed. Without the status filter, an unpublished draft could leak through a custom endpoint even while its usual page stays hidden.

public static function get_post( int $post_id ): ?WP_Post {
    $post = get_post( $post_id );
    if ( ! $post instanceof WP_Post ) {
        return null;
    }
    // Headless read surface: only published content is exposed.
    if ( 'publish' !== get_post_status( $post ) ) {
        return null;
    }
    return $post;
}

The argument schema is shared too: one definition of post_id typed as an integer with a minimum of 1 and a strict validate_callback. Every endpoint behaves identically on bad input, and the frontend handles one uniform 404 shape [1].

Duplicating the fetch-and-validate logic in each callback would work faster at first, but the cost appears when one rule changes. A single resolver means one place to tighten the rules and one place to look for bugs. The four endpoints under that namespace, meta, JSON-LD, the view counter, and related posts, all share the same entry path and were tested with the same pattern in the development stack: the meta response, the JSON-LD payload, a view count moving from zero to one, the related list, and a 404 rest_not_found for an unknown ID, all checked directly before the code went anywhere else.

The Transient Throttle: One Hour Is a Maximum, Not a Promise

The view counter uses a simple pattern: one transient per IP and post ID combination, keyed by an md5( $ip . ':' . $post_id ) hash, living for HOUR_IN_SECONDS. A hit on the transient means the count was already recorded for that IP within the last hour.

My initial assumption was plain: "one hour" means exactly one hour. The official transients documentation says otherwise: the expiration time is a maximum, with no guaranteed minimum. A transient can vanish early, and with an external object cache active it is not even guaranteed to live in the wp_options table, since it may move to memory [3].

The consequence: a throttle like this is best-effort. As a limiter for a view counter, the small deviation is acceptable; an occasional duplicate count breaks nothing. For billing or quotas that demand absolute accuracy, a transient is the wrong choice, and a dedicated table with proper indexes is more trustworthy.

The decision I made on that project: keep the throttle best-effort for the counter, and write the assumption into a code comment. A tool's limit should be acknowledged from the start, not discovered through an incident.

Sources

  1. WordPress Developer Resources, "Adding Custom Endpoints": developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints
  2. WordPress Developer Resources, register_rest_route(): developer.wordpress.org/reference/functions/register_rest_route
  3. WordPress Developer Resources, "Transients": developer.wordpress.org/apis/transients

Related articles