Could we help you? Please click the banners. We are young and desperately need the money
The WordPress REST API opens powerful opportunities for developers to build modern, decoupled, and interactive applications. Whether you're crafting a plugin that communicates with JavaScript or a theme that dynamically fetches content, mastering the REST API is a must. In this comprehensive guide, we’ll walk through how to leverage the WordPress REST API in both plugins and themes, create custom endpoints, and extend existing responses — with practical code examples and outputs.
The WordPress REST API provides endpoints for WordPress data types like posts, users, comments, media, and more. It allows you to interact with your WordPress site using HTTP requests and get JSON responses — making WordPress a powerful headless CMS or backend for modern apps.
GET https://yoursite.com/wp-json/wp/v2/posts
This returns a JSON array of posts:
[
{
"id": 1,
"title": { "rendered": "Hello World" },
"content": { "rendered": "<p>Welcome to WordPress!</p>" },
...
},
...
]
Plugins are the ideal place to register custom REST API routes and controllers. Let’s explore how to interact with and extend the API within a plugin.
You can enqueue a script and fetch data using JavaScript's fetch API.
// In your plugin file
function myplugin_enqueue_script() {
wp_enqueue_script(
'myplugin-api-fetch',
plugin_dir_url(__FILE__) . 'js/api-fetch.js',
array(),
'1.0',
true
);
}
add_action('wp_enqueue_scripts', 'myplugin_enqueue_script');
// js/api-fetch.js
fetch('/wp-json/wp/v2/posts')
.then(res => res.json())
.then(data => {
console.log('Fetched Posts:', data);
// Output to DOM
document.body.innerHTML += `<pre>${JSON.stringify(data, null, 2)}</pre>`;
});
Expected Output:
Fetched Posts: [
{
"id": 1,
"title": { "rendered": "Hello World" },
...
},
...
]
add_action('rest_api_init', function () {
register_rest_route('myplugin/v1', '/greeting', array(
'methods' => 'GET',
'callback' => 'myplugin_custom_greeting',
));
});
function myplugin_custom_greeting() {
return array('message' => 'Hello from my plugin!');
}
Expected Output (GET /wp-json/myplugin/v1/greeting):
{
"message": "Hello from my plugin!"
}
While plugins handle the logic, themes often use the REST API for dynamic front-end rendering.
// Place this in your theme's JS file
fetch('/wp-json/wp/v2/posts')
.then(res => res.json())
.then(posts => {
const container = document.getElementById('post-output');
posts.forEach(post => {
container.innerHTML += `<h3>${post.title.rendered}</h3><div>${post.excerpt.rendered}</div>`;
});
});
<div id="post-output"></div>
Expected Output in Theme:
Hello World
Welcome to WordPress!
Here’s how to create a custom POST route in your plugin to accept data:
add_action('rest_api_init', function () {
register_rest_route('myplugin/v1', '/submit-data', array(
'methods' => 'POST',
'callback' => 'myplugin_handle_data',
'permission_callback' => '__return_true',
));
});
function myplugin_handle_data($request) {
$params = $request->get_json_params();
return array('received' => $params);
}
POST Body Example:
{
"username": "devuser",
"feedback": "Great plugin!"
}
Expected Output:
{
"received": {
"username": "devuser",
"feedback": "Great plugin!"
}
}
add_action('rest_api_init', function () {
register_rest_field('post', 'custom_meta', array(
'get_callback' => function ($post_arr) {
return get_post_meta($post_arr['id'], '_my_custom_meta', true);
},
'schema' => null,
));
});
Expected API Output (in /wp-json/wp/v2/posts):
{
"id": 1,
"title": { "rendered": "Hello World" },
"custom_meta": "Custom Meta Value"
}
function myplugin_cached_response() {
$cache = get_transient('myplugin_cached_result');
if (!$cache) {
$cache = array('data' => rand(1, 9999)); // Simulated data
set_transient('myplugin_cached_result', $cache, 3600); // Cache for 1 hour
}
return $cache;
}
add_action('rest_api_init', function () {
register_rest_route('myplugin/v1', '/cached', array(
'methods' => 'GET',
'callback' => 'myplugin_cached_response',
));
});
Expected API Output (in /wp-json/myplugin/v1/cached):
Response:
{
"data": 5273
}
Protect endpoints with a permission check:
register_rest_route('myplugin/v1', '/secure-data', array(
'methods' => 'GET',
'callback' => 'myplugin_secure_data',
'permission_callback' => function () {
return current_user_can('edit_posts');
}
));
function myplugin_secure_data() {
return array('secret' => 'This is only for editors.');
}
Whether you’re building an AJAX-powered front end, a decoupled app, or extending the WordPress back end — the REST API is your gateway. By learning how to fetch, post, and extend the API with custom endpoints and permission checks, you unlock an entirely new level of power as a WordPress developer.
Remember: Keep endpoints efficient, cache when needed, and always use permission_callback for protected data.
Now it’s your turn — go build something amazing with the REST API!