This is How to Add Custom Endpoints for the WordPress REST API
As a WordPress developer, you may often find yourself needing to extend the core functionality of the WordPress REST API to fit the specific needs of your project. Whether you're building a web application, a mobile app, or an advanced website, having the ability to create custom API endpoints can be a game-changer.
In this article, we'll walk through the process of adding custom endpoints to the WordPress REST API step-by-step. By the end, you'll have the knowledge and code needed to create your own custom API endpoints and integrate them seamlessly into your WordPress website or application.
Understanding the WordPress REST API
The WordPress REST API is a powerful tool that allows developers to interact with WordPress sites programmatically. It provides a standardized way to retrieve, create, update, and delete content and data from a WordPress installation using HTTP requests.
The core WordPress REST API comes with a set of pre-defined endpoints that cover many common use cases, such as retrieving posts, pages, users, and media. However, there are often times when you'll need to extend the API to include your own custom functionality.
Creating Custom Endpoints
To add custom endpoints to the WordPress REST API, we'll create two new files within our WordPress theme's directory:
wp-content/themes/yourTheme/API/wp-rest-api-base.php
wp-content/themes/yourTheme/API/wp-rest-api-func.php
Then, we'll include these files in the functions.php
file of our current theme:
require get_parent_theme_file_path('API/wp-rest-api-base.php');
require get_parent_theme_file_path('API/wp-rest-api-func.php');
wp-rest-api-base.php
In this file, we'll define the base class for our custom API endpoints. This class will handle the registration of our custom routes and any necessary CORS (Cross-Origin Resource Sharing) configuration.
<?php
class ApiBaseController extends WP_REST_Controller {
//The namespace and version for the REST SERVER
var $my_namespace = 'api/v';
var $my_version = '1';
public function register_routes() {
$namespace = $this->my_namespace.$this->my_version;
register_rest_route($namespace, '/promotions', array(
array(
'methods' => 'POST',
'callback' => array(new ApiDefaultController('cms_promotions'), 'init'),
)
)
);
register_rest_route($namespace, '/location_based_notify', array(
array(
'methods' => 'GET',
'callback' => array(new ApiDefaultController('location_based_notify'), 'init'),
)
)
);
}
public function hook_rest_server() {
add_action('rest_api_init', array($this, 'register_routes'));
//add_action('rest_api_init', 'my_customize_rest_cors', 15);
}
public function my_customize_rest_cors() {
remove_filter('rest_pre_serve_request', 'rest_send_cors_headers');
remove_filter('rest_post_dispatch', 'rest_send_allow_header');
}
}
$ApiBaseController = new ApiBaseController();
$ApiBaseController->hook_rest_server();
In this file, we define the ApiBaseController
class, which extends the WP_REST_Controller
class provided by WordPress. This class is responsible for registering our custom API routes and handling any necessary CORS configuration.
The register_routes()
method is where we define our custom API endpoints. In this example, we're registering two endpoints:
/promotions
(POST method)
/location_based_notify
(GET method)
For each endpoint, we're creating a new instance of the ApiDefaultController
class (which we'll define in the next file) and passing a unique method name as a parameter. This will allow the ApiDefaultController
class to handle the logic for each endpoint.
wp-rest-api-func.php
In this file, we'll define the ApiDefaultController
class, which will handle the logic for our custom API endpoints.
<?php
class ApiDefaultController extends ApiBaseController
{
public $method;
public $response;
public function __construct($method)
{
$this->method = $method;
$this->response = array(
'Status' => false,
'StatusCode' => 0,
'StatusMessage' => 'Default'
);
}
private $status_codes = array(
'success' => true,
'failure' => 0,
'missing_param' => 150,
);
public function init(WP_REST_Request $request)
{
try {
if (!method_exists($this, $this->method)) {
throw new Exception('No method exists', 500);
}
$data = $this->{$this->method}($request);
$this->response['Status'] = $this->status_codes['success'];
$this->response['StatusCode'] = 1000;
$this->response['StatusMessage'] = 'success';
$this->response['Data'] = $data;
} catch (Exception $e) {
$this->response['Status'] = false;
$this->response['StatusCode'] = $e->getCode();
$this->response['StatusMessage'] = $e->getMessage();
}
return $this->response;
}
public function cms_promotions($request)
{
$data = array();
return $data;
/*
// Example of how to retrieve and process data from the request
$promotions = $request->get_param('promotions');
if (!$promotions) {
throw new Exception('Missing "promotions" parameter', $this->status_codes['missing_param']);
}
// Process the promotions data and return the result
$data = array(
'processed_promotions' => $promotions
);
return $data;
*/
}
public function location_based_notify($request)
{
$data = array();
return $data;
/*
// Example of how to retrieve and process data from the request
$location = $request->get_param('location');
if (!$location) {
throw new Exception('Missing "location" parameter', $this->status_codes['missing_param']);
}
// Process the location data and return the result
$data = array(
'location_based_notifications' => $this->getLocationBasedNotifications($location)
);
return $data;
*/
}
}
In this file, we define the ApiDefaultController
class, which extends the ApiBaseController
class we created earlier. This class is responsible for handling the logic for our custom API endpoints.
The __construct()
method initializes the $method
and $response
properties of the class, which will be used throughout the codebase.
The init()
method is called when a request is made to one of our custom API endpoints. It first checks if the requested method exists in the class, and if so, it calls that method and returns the resulting data. If an exception is thrown, it populates the $response
array with the appropriate error information.
The cms_promotions()
and location_based_notify()
methods are where you would implement the specific logic for your custom API endpoints. In this example, we've left them empty, but you would replace the placeholder code with your own implementation.
Accessing the Custom Endpoints
Once you've created the files and included them in your theme's functions.php
file, you can access your custom API endpoints using the following URLs:
- POST Method:
http://website.com/wp-json/api/v1/promotions
- GET Method:
http://website.com/wp-json/api/v1/location_based_notify
Remember, your custom methods should not return JSON data directly, as the WordPress REST API structure will handle that for you. Instead, your methods should return an array of data, and the REST API will automatically convert it to a JSON response.
Get a Free AI Website Audit
Automatically identify UX and content issues affecting your conversion rates with Flowpoint's comprehensive AI-driven website audit.
Conclusion
In this article, we've walked through the process of adding custom endpoints to the WordPress REST API. By creating two new files, wp-rest-api-base.php
and wp-rest-api-func.php
, and including them in your theme's functions.php
file, you can easily extend the functionality of the WordPress REST API to fit the specific needs of your project.
This approach gives you the flexibility to create custom API endpoints that can retrieve, create, update, and delete data in your WordPress installation, unlocking a world of possibilities for your web applications, mobile apps, and advanced websites. Flowpoint.ai can help you identify all the technical errors that are impacting conversion rates on your website and directly generate recommendations to fix them