To write a custom REST API endpoint in WordPress, you’ll need to use the WordPress REST API infrastructure. WordPress provides a powerful REST API that allows you to create custom endpoints for your specific needs. Here’s a step-by-step guide on how to create a custom REST API endpoint in WordPress:
1. Create a Plugin or Use Your Theme’s functions.php
:
First, you need to create a plugin or add the code to your theme’s functions.php
file. It’s recommended to use a plugin to keep the code separate and portable.
2. Define Your Custom Endpoint:
// In your plugin or functions.php
function custom_api_route() {
register_rest_route('custom/v1', '/example/', array(
'methods' => 'GET',
'callback' => 'custom_api_callback',
));
}
add_action('rest_api_init', 'custom_api_route');
In this example, we are registering a route with the base namespace custom/v1
and endpoint /example/
. The methods
parameter specifies which HTTP methods are allowed (e.g., 'GET'
, 'POST'
, 'PUT'
, 'DELETE'
). The callback
parameter points to the function that will handle the request.
3. Implement the Callback Function:
// Callback function for your custom endpoint
function custom_api_callback($data) {
$response = array(
'status' => 'success',
'message' => 'Custom API endpoint is working!',
'data' => $data,
);
return rest_ensure_response($response);
}
In this example, the custom_api_callback
function simply returns a response array. You can customize this function to perform any logic based on the data received in the request.
4. Access Your Custom Endpoint:
Now, you can access your custom API endpoint by making a request to the following URL:
https://yoursite.com/wp-json/custom/v1/example/
Replace yoursite.com
with your actual domain.
Notes:
- Always sanitize and validate input data to ensure security.
- You can use the
permission_callback
parameter when registering the route to control access to your custom endpoint. - You may need to handle authentication if your endpoint requires it.
- If your endpoint needs to accept data through POST or other methods, adjust the
'methods'
parameter accordingly.
This is a basic example, and you can expand it based on your specific requirements. The WordPress REST API is powerful and flexible, allowing you to create complex custom endpoints for your application.