Using WordPress ‘rest_api_init()’ PHP function

The rest_api_init() WordPress PHP function registers rewrite rules for the REST API.

Usage

add_action('init', 'rest_api_init');

Parameters

  • None

More information

See WordPress Developer Resources: rest_api_init()

Examples

Basic usage of rest_api_init()

In this example, we’ll register the REST API rewrite rules during the init action.

function myplugin_register_rest_api() {
  // Register the rewrite rules for the REST API.
  rest_api_init();
}

// Hook into the 'init' action to register the REST API.
add_action('init', 'myplugin_register_rest_api');

Adding a custom REST API endpoint

In this example, we’ll register a custom REST API endpoint to fetch information about books.

function myplugin_register_book_endpoint() {
  register_rest_route('myplugin/v1', '/books', array(
    'methods' => 'GET',
    'callback' => 'myplugin_get_books',
  ));
}

function myplugin_get_books() {
  // Fetch and return book data.
}

// Hook into 'rest_api_init' to register the custom endpoint.
add_action('rest_api_init', 'myplugin_register_book_endpoint');

Adding a custom REST API endpoint with parameters

In this example, we’ll register a custom REST API endpoint to fetch a specific book based on its ID.

function myplugin_register_book_by_id_endpoint() {
  register_rest_route('myplugin/v1', '/books/(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'myplugin_get_book_by_id',
  ));
}

function myplugin_get_book_by_id($request) {
  // Fetch and return book data based on the provided ID.
}

// Hook into 'rest_api_init' to register the custom endpoint.
add_action('rest_api_init', 'myplugin_register_book_by_id_endpoint');

Adding a custom REST API endpoint with authentication

In this example, we’ll register a custom REST API endpoint to update a book’s information. This endpoint will require authentication.

function myplugin_register_update_book_endpoint() {
  register_rest_route('myplugin/v1', '/books/(?P<id>\d+)', array(
    'methods' => 'PUT',
    'callback' => 'myplugin_update_book',
    'permission_callback' => 'myplugin_permission_check',
  ));
}

function myplugin_update_book($request) {
  // Update and return book data.
}

function myplugin_permission_check() {
  // Check if the user has the necessary permissions.
}

// Hook into 'rest_api_init' to register the custom endpoint.
add_action('rest_api_init', 'myplugin_register_update_book_endpoint');

Adding a custom REST API namespace

In this example, we’ll register a custom REST API namespace for a plugin.

function myplugin_register_namespace() {
  global $wp_rest_server;
  $wp_rest_server->register_route_namespace('myplugin/v1');
}

// Hook into 'rest_api_init' to register the custom namespace.
add_action('rest_api_init', 'myplugin_register_namespace');