Menü schliessen
Created: March 10th 2025
Last updated: April 16th 2025
Categories: Php,  Wordpress
Author: Ian Walser

Unlock the Full Power of the WordPress REST API: A Practical Guide for Plugin & Theme Developers (With Real Examples)

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

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.

What Is the WordPress REST API?

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.

Basic Example of a REST API Request

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>" },
    ...
  },
  ...
]

Using the REST API in WordPress Plugins

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.

1. Fetching API Data in Plugins (Client-Side JS)

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" },
    ...
  },
  ...
]

2. Registering a Custom Endpoint

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!"
}

Using the REST API in Themes

While plugins handle the logic, themes often use the REST API for dynamic front-end rendering.

1. Display Latest Posts in Theme

// 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!

Creating a REST API POST Endpoint

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!"
  }
}

Advanced Usage for Senior Developers

1. Register Custom Fields in Existing Endpoints

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"
}

2. Cache REST API Responses

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
}

3. Add Permission Callbacks

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.');
}

Conclusion

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!

Official WordPress Plugin and REST API Handbook