rest_api_init

Home » Hooks » rest_api_init

Hook Name: rest_api_init

WordPress is known for its flexibility and extensibility, thanks to its extensive use of hooks. One such powerful hook is rest_api_init. This hook is an essential part of the WordPress REST API infrastructure, allowing developers to register custom routes and endpoints for their REST API resources.

The rest_api_init hook is fired when the REST API is initialized, making it the perfect place to add custom endpoints or modify existing ones. By utilizing this hook, developers can extend the functionality of the REST API to suit their specific needs or integrate it with other plugins or custom code.

Developers can use the rest_api_init hook to register custom routes and endpoints using the register_rest_route() function. This function takes parameters such as the namespace, route, arguments, and callback function to handle the request. By providing a callback function, developers can define their own logic and response for the custom API endpoint.

Here’s an example usage code for the rest_api_init hook:

function custom_rest_route() {
    register_rest_route( 'my-plugin/v1', '/custom-endpoint', array(
        'methods' => 'GET',
        'callback' => 'custom_endpoint_callback',
    ) );
}
add_action( 'rest_api_init', 'custom_rest_route' );

function custom_endpoint_callback( $request ) {
    // Handle the custom API request and return the response
    return 'Hello, World!';
}

In the above example, we define a custom REST API endpoint under the namespace my-plugin/v1 with the route /custom-endpoint. The custom_endpoint_callback() function is responsible for handling the request and returning the desired response, which in this case is a simple "Hello, World!" message. The custom_rest_route() function is then hooked into rest_api_init using add_action() to register our custom endpoint.

By leveraging the rest_api_init hook, developers can extend the power of the WordPress REST API, creating tailored endpoints and expanding the capabilities of their websites or applications.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.