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 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 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 add_action( 'rest_api_init' , 'create_custon_endpoint' );
?> |
Complete Code: Below given the whole steps in one frame.
/* 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: