web developement

Creating a Custom REST API Endpoint in WordPress with PHP

Extending the WordPress REST API by creating custom endpoints can significantly enhance the functionality of your site. Whether you’re integrating with external applications or building unique features, custom endpoints allow seamless data interaction. This guide walks you through the process of creating a custom REST API endpoint using PHP in WordPress.

Why Create a Custom REST API Endpoint?

  • Custom Data Access – Retrieve or update specific data that the default WordPress API endpoints don’t handle.
  • Integration – Connect with external applications by exposing custom data formats.
  • Performance Optimization – Control exactly what data is queried and returned, ensuring efficient and lightweight responses.

Prerequisites

  • A WordPress installation (local or live).
  • Basic knowledge of PHP and WordPress development.
  • A child theme or custom plugin (recommended for best practices).

Step 1: Registering the Custom REST API Endpoint

The first step is to register your custom endpoint. This can be done by adding code to your theme’s functions.php file or within a custom plugin.

add_action('rest_api_init', 'register_custom_endpoint');

function register_custom_endpoint() {
    register_rest_route('custom/v1', '/data/', array(
        'methods' => 'GET',
        'callback' => 'handle_custom_data_request',
        'permission_callback' => '__return_true',  // Open for public, use proper validation in production
    ));
}

Explanation

  • rest_api_init – Hook that initializes the REST API.
  • register_rest_route – Registers a new REST route.
    • 'custom/v1' – Namespace/version.
    • '/data/' – The endpoint slug.
    • methods – HTTP method (GET, POST, etc.).
    • callback – Function that processes the request.
    • permission_callback – Defines who can access the endpoint.

Step 2: Handling the API Request

Now, let’s create the callback function that returns data when the endpoint is accessed.

function handle_custom_data_request($request) {
    $data = array(
        'message' => 'Hello, this is custom API data!',
        'time' => current_time('mysql'),
    );
    return rest_ensure_response($data);
}

Explanation

  • handle_custom_data_request – Handles incoming requests and returns a response.
  • current_time('mysql') – Retrieves the current time in MySQL format.
  • rest_ensure_response – Ensures the returned data is properly formatted as a REST response.

Step 3: Testing the Endpoint

After adding the code, visit your site’s URL:

https://yoursite.com/wp-json/custom/v1/data/

You should see a JSON response similar to:

{
  "message": "Hello, this is custom API data!",
  "time": "2025-01-05 15:00:00"
}

Step 4: Adding Parameters to the Endpoint

To make the endpoint more dynamic, let’s add parameters.

register_rest_route('custom/v1', '/data/', array(
    'methods' => 'GET',
    'callback' => 'handle_custom_data_request_with_params',
    'permission_callback' => '__return_true',
    'args' => array(
        'name' => array(
            'required' => false,
            'validate_callback' => function($param, $request, $key) {
                return is_string($param);
            },
        ),
    ),
));

function handle_custom_data_request_with_params($request) {
    $name = $request->get_param('name');
    $message = $name ? "Hello, $name!" : "Hello, visitor!";
    $data = array(
        'message' => $message,
        'time' => current_time('mysql'),
    );
    return rest_ensure_response($data);
}

Testing the Parameter:

https://yoursite.com/wp-json/custom/v1/data/?name=John

Response:

{
  "message": "Hello, John!",
  "time": "2025-01-05 15:05:00"
}

Conclusion

Creating custom REST API endpoints in WordPress allows for tailored data retrieval and interaction with external services. By following this guide, you can create dynamic, flexible endpoints that enhance your site’s functionality.


Leave a Reply

Your email address will not be published. Required fields are marked *