Created
October 18, 2018 17:45
-
-
Save junaidtk/2999f57c8b1003a4b4d40047891a45b2 to your computer and use it in GitHub Desktop.
REST API greeting using custom end point
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
We can create custom end point by using the register_rest_route() function. This function is need to call in rest_api_init hooks. | |
For this function register_rest_route(), the first argument is namespace, 2nd one is resource path or resource base and 3rd one is array option. | |
In array optuion we specify what method the end point can use and what call back is happen when an end point is matched. | |
/** | |
* This is our callback function that embeds our phrase in a WP_REST_Response | |
*/ | |
function prefix_get_endpoint_phrase() { | |
// rest_ensure_response() wraps the data we want to return into a WP_REST_Response, and ensures it will be properly returned. | |
return rest_ensure_response( 'Hello World, this is the WordPress REST API' ); | |
} | |
/** | |
* This function is where we register our routes for our example endpoint. | |
*/ | |
function prefix_register_example_routes() { | |
// register_rest_route() handles more arguments but we are going to stick to the basics for now. | |
register_rest_route( 'hello-world/v1', '/phrase', array( | |
// By using this constant we ensure that when the WP_REST_Server changes our readable endpoints will work as intended. | |
'methods' => WP_REST_Server::READABLE, | |
// Here we register our callback. The callback is fired when this endpoint is matched by the WP_REST_Server class. | |
'callback' => 'prefix_get_endpoint_phrase', | |
) ); | |
} | |
add_action( 'rest_api_init', 'prefix_register_example_routes' ); | |
So to see the hellow word phrase in REST API, please type the URL as. | |
http://sitename.com/wp-json/hello-world/v1/phrase/ | |
it will give the response like | |
"Hello World, this is the WordPress REST API". |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment