Quick & simple custom REST API routes for WordPress

WordPress REST API is a fantastic tool for delivering data either to the front end when you need to use it via JavaScript, or externally if you need to broadcast the data for other services/applications to consume. Fortunately, it’s also really easy to register custom REST API routes to display exactly what we need.

There are a few options available and if you need a robust system you might consider setting up a custom controller that extends the core WP_REST_Controller class. That’s a great approach if you need a lot of structure and control.

If, however, you need to fire up a route in a hurry, a simple script like the following does a fantastic job. This example will provide a nice output of JSON formatted data at the /wp-json/my-namespace/v1/some/route URI.

<?php
add_action( 'rest_api_init', function () {
register_rest_route( 'my-namespace/v1', 'some/route', [
'methods' => [ 'GET' ],
'permission_callback' => '__return_true',
'callback' => function () {
// You can return arrays or objects here — WordPress will
// format them for output as JSON.
return [
'some' => 'custom',
'data' => 'can',
'go' => 'here',
];
},
]
);
} );

About the author

Phil Kurth is a web developer living in Melbourne, Australia. Phil has a long history of WordPress development and enjoys building tools to empower others in their web design/development practice.

When not working with the web, Phil is usually spending time with his two young sons or is out hiking through the Australian bush.

Good dev stuff, delivered.

Product news, tips, and other cool things we make.

We never share your data. Read our Privacy Policy

© 2016 – 2024 Hookturn Digital. All rights reserved.