← Tous les articles

Custom WordPress REST API routes that don’t leave the door open

register_rest_route() takes ten lines, which is exactly the problem: a poorly protected route hands data to anyone who asks. permission_callback, schema-based argument validation, nonces from JavaScript and caching traps.

Custom WordPress REST API routes that don't leave the door open

Key points

  • permission_callback decides who may call the route, and it should check a specific capability, not just “logged in”.
  • Declaring a type for each argument in args lets WordPress reject bad requests before your code runs.
  • In the browser, cookie authentication only works when you send the X-WP-Nonce header.

A custom dashboard, a button that updates a status without a page reload, a mobile app reading content: as soon as a WordPress site has to talk to JavaScript, you end up registering your own REST routes. The API is pleasant to use, and when we review in-house themes and plugins we keep finding the same pattern: a route returning quotes or orders, guarded by '__return_true' because “it wouldn’t work otherwise”. This is how we write them instead.

A read route behind a real capability check

Say you have a devis (quote) post type and want to load one from a JavaScript interface:

add_action( 'rest_api_init', function () {
    register_rest_route( 'agence/v1', '/devis/(?P<id>d+)', [
        'methods'             => WP_REST_Server::READABLE,
        'callback'            => 'agence_get_devis',
        'permission_callback' => function ( WP_REST_Request $request ) {
            return current_user_can( 'edit_post', (int) $request['id'] );
        },
        'args'                => [
            'id' => [ 'type' => 'integer', 'minimum' => 1, 'required' => true ],
        ],
    ] );
} );

function agence_get_devis( WP_REST_Request $request ) {
    $post = get_post( $request['id'] );
    if ( ! $post || 'devis' !== $post->post_type ) {
        return new WP_Error( 'agence_not_found', 'Quote not found.', [ 'status' => 404 ] );
    }

    return rest_ensure_response( [
        'id'     => $post->ID,
        'title'  => get_the_title( $post ),
        'amount' => (float) get_post_meta( $post->ID, '_amount', true ),
        'status' => get_post_meta( $post->ID, '_status', true ),
    ] );
}

The line that matters is permission_callback. It receives the request, so you can check a capability on this specific object: edit_post with the ID accounts for authorship, role and any capability filters. A bare is_user_logged_in() would let any subscriber read everyone’s quotes.

Leave it out and WordPress has raised a “doing it wrong” notice since 5.5. For a route that really is public, write '__return_true' explicitly so whoever reviews the code knows it was deliberate.

Let the schema validate arguments

When an argument declares a type, an enum or a minimum, WordPress validates and casts the value before calling your function, and returns a readable 400 error otherwise. For a status update:

register_rest_route( 'agence/v1', '/devis/(?P<id>d+)/status', [
    'methods'             => WP_REST_Server::EDITABLE,
    'callback'            => 'agence_update_devis_status',
    'permission_callback' => fn( $request ) => current_user_can( 'edit_post', (int) $request['id'] ),
    'args'                => [
        'id'     => [ 'type' => 'integer', 'required' => true ],
        'status' => [
            'type'     => 'string',
            'enum'     => [ 'draft', 'sent', 'accepted', 'refused' ],
            'required' => true,
        ],
    ],
] );

Your callback no longer needs to worry about status being accepted<script>: either the value is in the list or the request never reaches you. On our projects this replaces a lot of scattered sanitize_text_field() calls.

Calling the route from JavaScript

This is where most routes end up wide open. A logged-in user calling the API with fetch() is treated as anonymous unless the request carries a nonce: WordPress deliberately ignores the session cookie without one, as CSRF protection. The capability check fails, a 401 comes back, and opening everything up looks like the quick fix. Pass a wp_rest nonce instead:

wp_enqueue_script( 'agence-devis', get_theme_file_uri( 'js/devis.js' ), [], '1.0', true );
wp_localize_script( 'agence-devis', 'agenceApi', [
    'root'  => esc_url_raw( rest_url( 'agence/v1/' ) ),
    'nonce' => wp_create_nonce( 'wp_rest' ),
] );
const res = await fetch(`${agenceApi.root}devis/${id}/status`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-WP-Nonce': agenceApi.nonce,
  },
  body: JSON.stringify({ status: 'accepted' }),
});

For external clients such as a mobile app or another server, cookies make no sense. Use WordPress’s built-in application passwords over HTTPS with Basic authentication.

Traps we run into

  • A page cache or CDN caching GET responses under /wp-json/, so one user receives a response built for someone else. Exclude private routes from caching.
  • A nonce printed into a page that is itself cached: it expires and calls start failing for everyone after a while.
  • Returning data “just in case”. Send only the fields the interface needs, not the whole object with its meta.

FAQ

Why not just use the built-in /wp/v2/ routes?

They’re fine for reading or editing standard posts. A dedicated route is better when the action carries business logic (changing a status, sending an email) or when you want tight control over what is exposed.

Should I disable the REST API for visitors?

Turning it off completely breaks the block editor and many plugins. Protect your own routes properly and limit what the public routes reveal instead.

Need a custom interface wired into your WordPress site, or a review of the routes you already have? We build and secure these integrations for our clients.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →