How to Create and Use Custom REST API Endpoints in WordPress?

How-to-Create-and-Use-Custom-REST-API-Endpoints-in-WordPress

WordPress has transitioned from being primarily used as a blogging platform to a fully functioning CMS. As such, it can serve up headless websites, mobile applications, third-party integrations, and much more. This flexibility is made possible by one of WordPress’s backbone features, the REST API.

Hire WordPress Developer

The WordPress REST API provides users with a number of default endpoints for working with WordPress data; however, there are many cases where you will need custom API endpoints to handle your unique business logic and retrieve the data you want, or to integrate with another system. The REST API allows developers to easily interact with your WordPress database by making standard HTTP requests. When developing dynamic functionality that requires frontend-backend interaction, you will often find that custom REST API endpoints become necessary.

In this tutorial blog post, we discuss how to create and use custom REST API endpoints within WordPress, using a simple example to illustrate the concepts presented.

Example to Create and Use Custom REST API Endpoints in WordPress

  1. Registering a Custom REST API Endpoint
add_action('rest_api_init', function ()
{
    register_rest_route('custom/v1', '/post-view/(?P<id>\d+)',
    [
        'methods'             => 'POST',
        'callback'            => 'custom_increment_post_view',
        'permission_callback' => '__return_true',
   ]);
});

Here,

  • rest_api_init runs when WordPress initializes the REST API
  • custom/v1 is the namespace (best practice for versioning)
  • /post-view/{id} is the endpoint path
  • POST method is used to update data
  • permission_callback allows public access
  1. Handling the REST API Request (Callback Function)
function custom_increment_post_view($request)
{
    $post_id = absint($request['id']);
    if (!$post_id || get_post_status($post_id) !== 'publish') {
        return new WP_Error('invalid_post', 'Invalid Post ID', ['status' => 400]);
    }

    $views = (int) get_post_meta($post_id, '_post_views', true);
    $views++;
    update_post_meta($post_id, '_post_views', $views);
    return rest_ensure_response([
        'post_id' => $post_id,
        'views'   => $views,
    ]);
}

Here,

  • absint() ensures the post ID is numeric
  • get_post_status() prevents counting drafts or private posts
  • get_post_meta() fetches stored views
  • update_post_meta() saves the incremented count
  • rest_ensure_response() ensures a valid JSON response
  1. Calling the API from the Frontend
add_action('wp_enqueue_scripts', function () {
    if (!is_single()) {
        return;
    }

    wp_enqueue_script('wp-api-fetch');
    wp_add_inline_script(
        'wp-api-fetch',
        "
        document.addEventListener('DOMContentLoaded', function () {
            fetch('" . esc_url_raw(rest_url('custom/v1/post-view/' . get_the_ID())) . "', {
                method: 'POST'
            });
        });
        "
    );
});

Here,

  • is_single() ensures the script runs only on post pages
  • wp-api-fetch is a core WordPress script (safe to attach inline JS)
  • fetch() sends a POST request to the custom endpoint
  • The API runs without reloading the page
  1. Displaying the Post View Count in the Theme
function custom_get_post_views()
{
    if (!is_single()) {
        return '';
    }
    $views = (int) get_post_meta(get_the_ID(), '_post_views', true);
    return '<p class="post-views"><strong>Views:</strong> ' . $views . '</p>';
}

Now use <?php echo custom_get_post_views();?> in your theme.

Result:

result

The custom REST API endpoint in this article:

  • Tracks how many times a post is viewed
  • Increments the view count each time a post loads
  • Stores the count using post meta
  • Displays the total views on the frontend
  • Uses REST API instead of admin-ajax.php

Real-Life Use Cases:

This same custom REST API pattern is widely used across WordPress projects.

  • Post & Page View Tracking
  • WooCommerce Product Analytics
  • Favorites & Wishlist Features
  • Any Custom Plugin Development

Conclusion:

The custom REST API endpoints are among the many options available for integrating WordPress with modern applications and extending WordPress’ capabilities. They allow you to build mobile apps, build a headless content management system (CMS), or develop custom dashboards, among other things, by leveraging WordPress REST APIs to manage the way your data is exposed and utilized.

If you adhere to best-practices to ensure security and create scalable and adaptable solutions, your WordPress site will be ready for the future!

FAQ

1. What do custom REST API endpoints mean in WordPress?

Custom REST API endpoints are defined routes by developers to manage or expose your WordPress data outside of what is offered through the native REST API capabilities.

2. Where is the best place to store the code for custom REST API endpoints in WordPress?

For maintaining your code base, it is highly recommended that you place custom REST API endpoint code in a custom plugin rather than in your theme’s functions.php file. This allows for ease of maintenance and reference, as well as reusability of the code if you decide to change your theme or redevelop your site.

3. Is it possible to create REST API endpoints for custom post types?

Yes, it is a simple process to create custom REST API endpoints for custom post types utilizing either the WP_Query or get_posts() functions.

4. Is the WordPress REST API enabled by default?

Yes, the REST API is enabled by default in modern WordPress versions unless explicitly disabled.

Previous Article

Top Adobe Commerce Development Companies in UK

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨