Created
August 13, 2025 18:17
-
-
Save kpirnie/84f411086845a75298de9f0b56d17316 to your computer and use it in GitHub Desktop.
WordPress - REST Request?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * is_rest_request | |
| * | |
| * this method attempts to determine if the current request is for the REST API or not | |
| * based on a fiew factors | |
| * | |
| * @since 7.4 | |
| * @access public | |
| * @author Kevin Pirnie <[email protected]> | |
| * @package Protect Your REmote | |
| * | |
| * @return bool This method returns a boolean value | |
| * | |
| */ | |
| public static function is_rest_request( ) : bool { | |
| // hold our return, default as false | |
| $_ret = false; | |
| // our full requested URI | |
| $_uri = ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] === 'on' ? "https" : "http" ) . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; | |
| // check if the REST_REQUEST constant is defined, and see if there is a rest_route attached to it | |
| if( defined( 'REST_REQUEST' ) && REST_REQUEST || isset( $_GET['rest_route'] ) && strpos( $_GET['rest_route'] , '/', 0 ) === 0 ) { | |
| // there is, return true | |
| $ret = true; | |
| } | |
| // check the wp_rewrite global | |
| global $wp_rewrite; | |
| // if it's not currently set | |
| if( ! $wp_rewrite ) { | |
| // set it | |
| $wp_rewrite = new WP_Rewrite( ); | |
| } | |
| // parse the rest URL, if it exists | |
| $_rest_url = wp_parse_url( trailingslashit( rest_url( ) ) ); | |
| // parse the current URL, if it exists | |
| $_current_url = wp_parse_url( $_uri ); | |
| // the current ur path | |
| $_current_url_path = ( $_current_url['path'] ) ?? null; | |
| // check if the rest url matches the current url | |
| if( in_array( $_current_url_path, $_rest_url ) ) { | |
| // it does not, return true | |
| $_ret = true; | |
| } | |
| // get the rest prefix, if it exists | |
| $_rest_prefix = rest_get_url_prefix( ); | |
| // set the return if the prefix matches | |
| $_ret = false !== strpos( $_uri, $_rest_prefix ); | |
| // return our return | |
| return $_ret; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment