Add Custom REST API Route WordPress

Add Custom REST API Route WordPress

This blog describes about – how we can add custom REST API routes in WordPress. The use of API is very common now a days. So, when we work with API’s we need some custom routes also with default ones so that we can facilitate intended tasks.

When we add our custom routes, its important that we don’t affect the default one’s. We should add new routes in with default one’s not in place of default routes. Here we go,

We use rest_api_init hook which fires when preparing to serve an API request.

add_action( 'rest_api_init', 'wk_register_custom_routes' );

Now, we register our route in callback function of above action using function register_rest_route –

function wk_register_custom_routes() {
   register_rest_route( 'package/v1', 'abc/xyz', array(
       'methods'  => GET/POST,
       'callback' => 'wk_route_callback' ),
   ) );
}

Here, first parameter represents namespace which should unique to plugin, second is the base url for our route. Third parameter is the argument array. We can use fourth parameter also which is optional i.e override, means if route already exists the route will be override if set to true.

In methods argument we write GET/POST, here we can also use WP_REST_Server constants, e.g  WP_REST_Server::CREATABLE means PUT/POST,  WP_REST_Server::READABLE means GET, etc.

Using the callback function we specified while registering the route we can perform actions we want to do using registered route.

function wk_route_callback() {
   // code
}

Reference https://developer.wordpress.org/reference/functions/register_rest_route/.

Support

Still have any issue feel free to add a ticket and let us know your views to make the code better https://webkul.uvdesk.com/en/customer/create-ticket/

Thanks for Your Time! Have a Good Day!