Rest API – Does something like is_rest() exist

To solve this problem I wrote a simple custom function based on the assumption that if the URI being requested falls within the REST API URL of the WordPress site, it follows that it is a REST API request.

It is not a valid endpoint, or certified, to determine this function. The question is: is the URL a possible REST API URL?

function isRestUrl() {
    $bIsRest = false;
    if ( function_exists( 'rest_url' ) && !empty( $_SERVER[ 'REQUEST_URI' ] ) ) {
        $sRestUrlBase = get_rest_url( get_current_blog_id(), "" );
        $sRestPath = trim( parse_url( $sRestUrlBase, PHP_URL_PATH ), "" );
        $sRequestPath = trim( $_SERVER[ 'REQUEST_URI' ], "" );
        $bIsRest = ( strpos( $sRequestPath, $sRestPath ) === 0 );
    return $bIsRest;

if your $_SERVER['REQUEST_URI'] is not populated properly, this function will still return falseregardless.

There is no hard-coding of URLs, so if you change your API URL base for some reason, it will be optimized.

Leave a Comment