Using WordPress ‘register_rest_route()’ PHP function

The register_rest_route() WordPress PHP function registers a REST API route.

Usage

register_rest_route( $route_namespace, $route, $args = array(), $override = false );

Parameters

  • $route_namespace (string) Required: The first URL segment after the core prefix. Should be unique to your package/plugin.
  • $route (string) Required: The base URL for the route you are adding.
  • $args (array) Optional: Either an array of options for the endpoint or an array of arrays for multiple methods. Default: array()
  • $override (bool) Optional: If the route already exists, should we override it? True overrides, false merges (with newer overriding if duplicate keys exist). Default: false

More information

See WordPress Developer Resources: register_rest_route()
Important: Do not use before the rest_api_init hook.

Examples

Register a simple GET route

This example registers a route that responds to a GET request and returns a list of items.

add_action( 'rest_api_init', function () {
  register_rest_route( 'my-plugin/v1', '/items', array(
    'methods'  => 'GET',
    'callback' => 'get_items'
  ));
});

function get_items() {
  // Code to get items
}

Register a POST route

This example registers a route that creates an item when a POST request is made.

add_action( 'rest_api_init', function () {
  register_rest_route( 'my-plugin/v1', '/items', array(
    'methods'  => 'POST',
    'callback' => 'create_item'
  ));
});

function create_item() {
  // Code to create an item
}

Register a route with multiple methods

This example registers a route that supports both GET and POST methods.

add_action( 'rest_api_init', function () {
  register_rest_route( 'my-plugin/v1', '/items', array(
    'methods'  => array( 'GET', 'POST' ),
    'callback' => 'handle_item_request'
  ));
});

function handle_item_request() {
  // Code to handle both GET and POST requests
}

Register a route with permission callback

This example registers a public route with a permission callback.

add_action( 'rest_api_init', function () {
  register_rest_route( 'my-plugin/v1', '/items', array(
    'methods'  => 'GET',
    'callback' => 'get_items',
    'permission_callback' => '__return_true'
  ));
});

function get_items() {
  // Code to get items
}

Register a route with arguments validation

This example registers a route with arguments validation for a GET request.

add_action( 'rest_api_init', function () {
  register_rest_route( 'my-plugin/v1', '/items/(?P<id>\d+)', array(
    'methods'  => 'GET',
    'callback' => 'get_item_by_id',
    'args' => array(
      'id' => array(
        'validate_callback' => function($param) {
          return is_numeric($param);
        }
      )
    )
  ));
});

function get_item_by_id( $request ) {
  // Code to get item by id
}