Using WordPress ‘get_rest_url()’ PHP function

The get_rest_url() WordPress PHP function retrieves the URL to a REST endpoint on a site. The returned URL is NOT escaped.

Usage

get_rest_url( $blog_id, $path, $scheme )

Example:
Input: get_rest_url(null, 'wp/v2/posts')
Output: https://example.com/wp-json/wp/v2/posts

Parameters

  • $blog_id int|null (Optional) – Blog ID. Default of null returns URL for the current blog. Default: null
  • $path string (Optional) – REST route. Default: ‘/’
  • $scheme string (Optional) – Sanitization scheme. Default: ‘rest’

More information

See WordPress Developer Resources: get_rest_url

Examples

Get the base REST URL

This code retrieves the base REST URL for the current blog.

$base_rest_url = get_rest_url();
// Output: https://example.com/wp-json/

Get the REST URL for a specific blog

This code retrieves the REST URL for a specific blog with an ID of 2.

$blog_id = 2;
$specific_blog_rest_url = get_rest_url($blog_id);
// Output: https://example2.com/wp-json/

Get the REST URL for a specific route

This code retrieves the REST URL for the “wp/v2/posts” route on the current blog.

$route = 'wp/v2/posts';
$route_rest_url = get_rest_url(null, $route);
// Output: https://example.com/wp-json/wp/v2/posts

Get the REST URL with a custom sanitization scheme

This code retrieves the REST URL for the current blog using the ‘https’ sanitization scheme.

$scheme = 'https';
$custom_scheme_rest_url = get_rest_url(null, '/', $scheme);
// Output: https://example.com/wp-json/

Get the REST URL for searching posts

This code retrieves the REST URL for the “wp/v2/search” route on the current blog.

$search_route = 'wp/v2/search';
$search_rest_url = get_rest_url(null, $search_route);
// Output: https://example.com/wp-json/wp/v2/search