Permission callbacks, argument schemas, and nonces for a custom endpoint. WordPress rewards developers who work with its APIs instead of around them. Almost every problem we have debugged in client projects started with a shortcut that bypassed a core function.
The WordPress way
Register things on the right hook, pass complete arguments, and let core handle the rest. It is more typing up front, but the result survives updates and plays nicely with other plugins.
add_action( 'rest_api_init', function () {
register_rest_route( 'shipwright/v1', '/bookmarks/(?P<id>d+)', [
'methods' => 'POST',
'callback' => 'shipwright_save_bookmark',
'permission_callback' => fn () => current_user_can( 'read' ),
'args' => [
'id' => [ 'validate_callback' => fn ( $v ) => is_numeric( $v ) ],
],
] );
} );
Registering it properly
Every endpoint and form needs three things: a capability check, a nonce or equivalent, and sanitisation on the way in with escaping on the way out. Skipping any one of them is how sites get compromised.
- Check capabilities before doing anything.
- Verify a nonce on every state-changing request.
- Sanitise input and escape output, always.
- Script test sites with WP-CLI.
Security checklist
WP-CLI makes all of this faster to test. We script the setup of a fresh site for every experiment so nothing depends on the state of a long-lived development database.
Before you ship this
A permission_callback that returns true makes the route public. That is fine for read-only data, but never for anything that writes.
Programs must be written for people to read, and only incidentally for machines to execute.
Harold Abelson, Structure and Interpretation of Computer Programs, 1985
Wrapping up
Questions, corrections, and war stories are welcome in the comments. Several of our best follow-up posts started as a reader pointing out something we had missed.
How does this hold up on older Safari versions? That is where we always get burned.
Solid write-up. The warning about caching bit us hard last year.
Clear, practical, no fluff. More of this, please.