Skip to content

Instantly share code, notes, and snippets.

@matzeeable
Last active February 22, 2024 20:20
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save matzeeable/dfd82239f48c2fedef25141e48c8dc30 to your computer and use it in GitHub Desktop.
Save matzeeable/dfd82239f48c2fedef25141e48c8dc30 to your computer and use it in GitHub Desktop.
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 and check if `rest_route` starts with `/`
* 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( $_GET['rest_route'] , '/', 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;
}
}
@matzeeable
Copy link
Author

Updated. I should definitely not update gist on my smartphone... :D

@gitgetgotgotten
Copy link

I don't understand what #3 is doing there!

@kagg-design
Copy link

@gitgetgotgotten Look at the code of rest_url() used in line 28.

@gitgetgotgotten
Copy link

@kagg-design Aha, thank you!

@fmurdeni
Copy link

fmurdeni commented Sep 25, 2023

thanks it works for me!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment