WordPress ships with a REST API that covers posts, pages, media, users and taxonomies, and for a lot of sites that is all the front end or the mobile app ever needs. The moment you need something shaped differently, a search endpoint that returns only what the chatbot wants, a feed of a custom post type with its meta already joined, a lightweight list for a headless front end, you need a custom endpoint. Writing one takes twenty lines. Writing one that does not leak drafts, fall over under load, or accept anything a stranger sends takes a bit more care, and that care is what this piece is about.
When a custom endpoint is the right answer
Three situations come up repeatedly.
A headless or partly headless front end needs data in a shape the default endpoints do not provide, or needs it in one request instead of five. The setup side of that is in headless WordPress with Next.js.
An AI feature needs clean content. A chatbot grounded in the site, of the kind described in how to build a RAG chatbot on your own website content, wants plain text with headings and no shortcodes, not rendered HTML with a cookie banner in it.
An internal tool or an external system needs to read or write something specific: a lead form submission, a stock level, a list of published case studies for the sales deck. A dedicated endpoint with a narrow contract is safer than opening the general API wider.
If the default endpoints already return what you need and the problem is only the field list, the _fields parameter on the built-in routes may be enough and you can stop reading.
Registering a route properly
Every route lives under a namespace with a version, so that it can change later without breaking what already uses it.
<?php
add_action( 'rest_api_init', function () {
register_rest_route( 'brilad/v1', '/guides', array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'brilad_get_guides',
'permission_callback' => '__return_true',
'args' => array(
'topic' => array(
'type' => 'string',
'required' => false,
'sanitize_callback' => 'sanitize_title',
'validate_callback' => function ( $value ) {
return strlen( $value ) <= 60;
},
),
'page' => array(
'type' => 'integer',
'default' => 1,
'minimum' => 1,
),
),
) );
} );
Three things are doing work here. The method is declared, so a POST to a read route is refused before your code runs. Each argument has a type, a sanitiser and a validator, so your callback receives clean values and never has to check them itself. And the permission callback is explicit, which for a public read route is the only situation where returning true is acceptable.
The callback, and what it must not return
<?php
function brilad_get_guides( WP_REST_Request $request ) {
$args = array(
'post_type' => 'guide',
'post_status' => 'publish',
'posts_per_page' => 20,
'paged' => $request->get_param( 'page' ),
'no_found_rows' => false,
);
if ( $request->get_param( 'topic' ) ) {
$args['tax_query'] = array( array(
'taxonomy' => 'topic',
'field' => 'slug',
'terms' => $request->get_param( 'topic' ),
) );
}
$query = new WP_Query( $args );
$items = array();
foreach ( $query->posts as $post ) {
$items[] = array(
'id' => $post->ID,
'title' => get_the_title( $post ),
'url' => get_permalink( $post ),
'modified' => get_post_modified_time( 'c', true, $post ),
'summary' => wp_strip_all_tags( get_the_excerpt( $post ) ),
);
}
$response = new WP_REST_Response( $items, 200 );
$response->header( 'X-WP-Total', (int) $query->found_posts );
$response->header( 'X-WP-TotalPages', (int) $query->max_num_pages );
return $response;
}
The post status is pinned to published. This is the line people forget, and the result is an endpoint that cheerfully lists scheduled and draft posts to anyone who asks, including their titles and their slugs. On a site that schedules content weeks ahead, that is a leak of the editorial calendar to competitors and a source of crawled URLs that return nothing yet.
The output is built field by field rather than returning the post object. A post object contains the author’s login name, the raw content with any private shortcodes, and whatever meta happens to be attached. Return only what the consumer needs.
The total count headers follow the convention the built-in endpoints use, so any client that already paginates the core API paginates yours.
Permissions, in order of strictness
For anything that writes, or reads anything not already public, the permission callback does real work.
<?php
'permission_callback' => function ( WP_REST_Request $request ) {
return current_user_can( 'edit_posts' );
},
How the user gets authenticated depends on who is calling. A logged-in browser session uses a nonce sent in the request header. An external system uses an application password over HTTPS, which gives it a real user with real capabilities you can restrict. Build a dedicated user for each integration with the minimum role that works, so a leaked credential has a small blast radius and a clear audit trail.
Never implement your own token check against a value in the options table. It bypasses everything WordPress already does for session handling and it will be weaker than the application password mechanism you were trying to avoid.
For public write endpoints such as a form submission, there is no user, so the protection is rate limiting, input validation and a spam check, plus a permission callback that still returns true deliberately rather than by default. The wider picture is in website security that protects your SEO.
Caching the response
A public read endpoint should be cacheable, and most are not because nobody sets the headers.
<?php
$response->header( 'Cache-Control', 'public, max-age=300, stale-while-revalidate=600' );
$response->header( 'Last-Modified', gmdate( 'D, d M Y H:i:s', $latest_modified ) . ' GMT' );
With that in place, the CDN or page cache in front of the site serves the endpoint without touching PHP, which matters when a front end calls it on every page view. Set the lifetime from how often the underlying content changes, and clear it when a post in that type is saved, through the same hooks you use to purge pages.
Inside WordPress, wrap expensive queries in a transient keyed on the request parameters, and invalidate the transient on save. An endpoint that runs a meta query across ten thousand posts on every call is the one that takes the site down during a traffic spike, and the fix is one transient. Performance on the page side is covered in Core Web Vitals for WordPress without plugin overload.
An endpoint for machines that read
A pattern we use on content sites: an endpoint that returns a page as clean text with its headings, for a chatbot, an internal search index or an assistant that has been given access to the site’s data. It strips shortcodes, renders blocks, removes scripts, and returns the result with the canonical URL and the modified date.
The same output can be served as a Markdown version of the page at a predictable address, which some AI crawlers prefer. Doing this at the Next.js layer is described in how to add llms.txt and Markdown page versions; in WordPress it is a route that takes a post identifier or slug and runs the content through the same cleaning function.
Keep this endpoint to published content only, and consider whether it should be public at all. If it exists to feed your own systems, authenticate it. If it exists to be found, make sure it is linked from somewhere and declared in your crawler guidance. The safety side of letting an agent read site data is in how to build AI agents that use your website’s data safely.
Declaring the schema
Each route can declare the shape of its response. It takes ten minutes, it makes the route self-documenting at the API index, and it lets client generators and validators do their job.
<?php
'schema' => function () {
return array(
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => 'guide',
'type' => 'object',
'properties' => array(
'id' => array( 'type' => 'integer' ),
'title' => array( 'type' => 'string' ),
'url' => array( 'type' => 'string', 'format' => 'uri' ),
'modified' => array( 'type' => 'string', 'format' => 'date-time' ),
'summary' => array( 'type' => 'string' ),
),
);
},
Errors that mean something
Return a WP_Error with a code, a message and a status rather than an empty array or a two hundred with an error string in it. A client that gets a four hundred with a readable code can handle it; a client that gets an empty success has no idea anything went wrong.
Do not include stack traces, query text or file paths in error messages on a production site. The default behaviour is sensible; custom code that catches an exception and returns its message to the caller is where paths leak.
Testing before it ships
- Call the route with no parameters, then with each parameter at its limits and beyond. The validators should refuse the bad ones with a four hundred.
- Create a draft and a scheduled post in the type, then call the route anonymously. Neither should appear.
- Call a write route with no credentials, with a subscriber’s credentials, and with the intended role. Only the last should succeed.
- Check the response headers for cache control and the totals.
- Load the route a few hundred times and watch the query count. If it is doing the same queries every time, add the transient.
- Confirm the route appears at the API index with its schema, then decide whether it should, and hide it from the index if it is internal.
What is a waste of effort
Building a custom endpoint to avoid learning the built-in ones. The core routes handle filtering, fields, embedding and pagination well, and a custom route that reinvents them badly is work with no return.
Putting endpoints in the theme. They stop working when the theme changes. They belong in a small plugin.
Permission callbacks that return true because the developer could not get authentication working. Fix the authentication.
Unversioned namespaces. The first breaking change will teach you why.
A sensible order of work
- Confirm the built-in routes cannot do it with fields and filters.
- Define the contract: method, arguments, response shape, who may call it.
- Register the route in a plugin under a versioned namespace with typed, validated arguments.
- Write the callback to return only the fields in the contract, from published content only.
- Set the permission callback to the real check, and create a dedicated user for any external caller.
- Add cache headers and a transient, with invalidation on save.
- Declare the schema, return proper errors, and run the six tests.
If your front end or your AI features are hammering the general API for data that should have had its own route, get in touch.