Friday, August 29, 2025
HomeLanguagesWordPress Create custom REST endpoint

WordPress Create custom REST endpoint

In this article, we will see how to create a custom REST endpoint in WordPress. WordPress is not only used for blogging and simple site platform. Now it’s used for large-scale enterprise projects and even a headless CMS. So if you are using WordPress as a headless CMS, you must know how to work with the REST APIs.

WordPress gives various functions to work on REST API. Let’s take a look at how you can easily create your custom endpoint.

We will use a rest_api_init action hook, and register_rest_route() inbuild function to create our custom endpoint.

Steps to Create a custom REST endpoint: You need to add this code to the theme’s functions.php file.

Step 1: Create a function that registers the REST route with the register_rest_route() function.

PHP




<?php
function create_custon_endpoint(){
    register_rest_route(
        'wp/v2',
        '/custom-ep',
        array(
            'methods' => 'GET',
            'callback' => 'get_response',
        )
    );
}
?>


This function’s first parameter is namespace ‘wp/v2’, the second parameter is endpoint name ‘/custom-ep’ and the third parameter is an array where you can add methods like GET, POST, DELETE, etc., and a callback function. You can customize these values according to your need.

For more details, you can check the document.

Step 2: Create callback function get_response().

PHP




<?php
function get_response() {
    // Your code...
    return 'This is your data!';
}
?>


In this function, you can do whatever you want to add to your endpoint.

Step 3: Add action hook rest_api_init which will run our function create_custon_endpoint on initialization of REST API on WordPress.

PHP




<?php
add_action( 'rest_api_init', 'create_custon_endpoint');
?>


Complete Code: Below given the whole steps in one frame.

PHP




/* Create Custom Endpoint */
add_action( 'rest_api_init', 'create_custon_endpoint' );
 
function create_custon_endpoint(){
    register_rest_route(
        'wp/v2',
        '/custom-ep',
        array(
            'methods' => 'GET',
            'callback' => 'get_response',
        )
    );
}
 
function get_response() {
    // your code
    return 'This is your data!';
}


Output:
 

endpoint’s response

RELATED ARTICLES

Most Popular

Dominic
32249 POSTS0 COMMENTS
Milvus
80 POSTS0 COMMENTS
Nango Kala
6617 POSTS0 COMMENTS
Nicole Veronica
11789 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11838 POSTS0 COMMENTS
Shaida Kate Naidoo
6731 POSTS0 COMMENTS
Ted Musemwa
7011 POSTS0 COMMENTS
Thapelo Manthata
6688 POSTS0 COMMENTS
Umr Jansen
6701 POSTS0 COMMENTS