Using WordPress ‘rest_api_loaded()’ PHP function

The rest_api_loaded() WordPress PHP function loads the REST API.

Usage

$result = rest_api_loaded();

Parameters

There are no parameters for this function.

More information

See WordPress Developer Resources: rest_api_loaded()

Examples

Load REST API and Check if Loaded

Check if the REST API is loaded, and if not, load it.

add_action('init', 'my_rest_api_check_and_load');
function my_rest_api_check_and_load() {
  if (!rest_api_loaded()) {
    rest_api_loaded();
  }
  echo 'REST API is loaded';
}

Conditionally Load REST API

Load the REST API only for logged-in users.

add_action('init', 'my_conditional_rest_api_load');
function my_conditional_rest_api_load() {
  if (is_user_logged_in()) {
    rest_api_loaded();
  }
}

Load REST API and Flush Rewrite Rules

Load the REST API and flush rewrite rules to refresh permalinks.

add_action('init', 'my_rest_api_load_and_flush');
function my_rest_api_load_and_flush() {
  rest_api_loaded();
  flush_rewrite_rules();
}

Load REST API on Specific Page

Load the REST API only on the ‘about’ page.

add_action('wp', 'my_rest_api_load_on_about_page');
function my_rest_api_load_on_about_page() {
  if (is_page('about')) {
    rest_api_loaded();
  }
}

Add Custom Endpoint and Load REST API

Create a custom endpoint and load the REST API.

add_action('rest_api_init', 'my_custom_endpoint');
function my_custom_endpoint() {
  register_rest_route('my_namespace/v1', '/my_data', array(
    'methods' => 'GET',
    'callback' => 'my_custom_endpoint_callback',
  ));
  rest_api_loaded();
}

function my_custom_endpoint_callback() {
  return array('data' => 'Hello, World!');
}