How to Create a Custom REST API Endpoint in WordPress ?
Hook into rest_api_init
:
Register your custom endpoint.
function register_custom_api_endpoint() {
register_rest_route( 'myplugin/v1', '/data/', array(
'methods' => 'GET', // Or 'POST', 'PUT', 'DELETE'
'callback' => 'custom_api_endpoint_callback',
'permission_callback' => '__return_true', // Or a custom permission check function
));
}
add_action( 'rest_api_init', 'register_custom_api_endpoint' );
Here,
myplugin/v1 -> The namespace and version of your API.
/data -> The endpoint URL.
methods -> The allowed HTTP methods (GET, POST etc ).
callback -> The function that will run when the endpoint is called.
permission_callback -> Function to control access.
Create the Callback Function: The callback where your logic goes. You can return any data.
function custom_api_endpoint_callback( $request ) {
return array(
'status' => 'success',
'message' => 'Hello World',
);
}
Access Endpoint:
https://example.com/wp-json/myplugin/v1/data