Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Checks if the current request is a WP REST API request.
<?php
if ( !function_exists( 'is_rest' ) ) {
/**
* Checks if the current request is a WP REST API request.
*
* Case #1: After WP_REST_Request initialisation
* Case #2: Support "plain" permalink settings
* Case #3: It can happen that WP_Rewrite is not yet initialized,
* so do this (wp-settings.php)
* Case #4: URL Path begins with wp-json/ (your REST prefix)
* Also supports WP installations in subfolders
*
* @returns boolean
* @author matzeeable
*/
function is_rest() {
if (defined('REST_REQUEST') && REST_REQUEST // (#1)
|| isset($_GET['rest_route']) // (#2)
&& strpos( trim( $_GET['rest_route'], '\\/' ), rest_get_url_prefix( ) , 0 ) === 0)
return true;
// (#3)
global $wp_rewrite;
if ($wp_rewrite === null) $wp_rewrite = new WP_Rewrite();
// (#4)
$rest_url = wp_parse_url( trailingslashit( rest_url( ) ) );
$current_url = wp_parse_url( add_query_arg( array( ) ) );
return strpos( $current_url['path'], $rest_url['path'], 0 ) === 0;
}
}
@andrewmclagan

This comment has been minimized.

Copy link

andrewmclagan commented Sep 5, 2019

There are some performance improvements to be had here.

@matzeeable

This comment has been minimized.

Copy link
Owner Author

matzeeable commented Sep 5, 2019

Hi! What exactly can be improved here? Just let me know :-)

@andrewmclagan

This comment has been minimized.

Copy link

andrewmclagan commented Sep 8, 2019

Before calling $prefix = rest_get_url_prefix( ); you can short circuit the return value when REST_REQUEST is defined. No need to call that function until later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.