Function and usage of register_rest_route() in wordpress

Question

Answers ( 1 )

    0
    2024-01-08T12:08:53+00:00

    The register_rest_route() function in WordPress is used for registering a new REST API route. Here's a detailed explanation of its function and usage:

    Function:

    Registers a REST API route.

    Description:

    • Important: This function should not be used before the rest_api_init hook in WordPress.
    • It allows developers to register new routes for the WordPress REST API.

    Parameters:

    1. $route_namespace (string, required):

      • The first URL segment after the core prefix.
      • It should be unique to your package or plugin.
      • This parameter helps in organizing the API routes under a specific namespace.
    2. $route (string, required):

      • The base URL for the route you are adding.
      • This is the path of the endpoint under the given namespace.
    3. $args (array, optional):

      • An array of options for the endpoint or an array of arrays for multiple methods.
      • Default value is an empty array.
      • Options can include methods (GET, POST, etc.), callback functions for handling requests, permission callbacks, and more.
    4. $override (bool, optional):

      • Determines if the existing route should be overridden if it already exists.
      • true means it will override, false means it will merge. In case of merging, newer entries will override duplicate keys.
      • Default value is false.

    Return:

    • bool: Returns true on successful registration, false on error.

    Sample Usage:

    Here's an example of how register_rest_route() might be used in a WordPress plugin:

    add_action( 'rest_api_init', function () {
        register_rest_route( 'myplugin/v1', '/myendpoint', array(
            'methods' => 'GET',
            'callback' => 'my_custom_function',
        ));
    });
    
    function my_custom_function( WP_REST_Request $request ) {
        // Handle the request and return response
        return new WP_REST_Response( 'Hello World', 200 );
    }
    

    In this example:

    • The route is registered under the namespace myplugin/v1.
    • The endpoint /myendpoint is being added.
    • It accepts GET requests and is handled by the function my_custom_function.
    • The my_custom_function takes a WP_REST_Request object and returns a WP_REST_Response.

    Remember, register_rest_route() should always be called within the context of the rest_api_init action hook for proper initialization and registration in the WordPress lifecycle.

Leave an answer