Last active
August 29, 2015 14:23
-
-
Save resarahman/703099894cb8ca812601 to your computer and use it in GitHub Desktop.
Determine if WordPress AJAX request is a backend of frontend request. original link http://snippets.khromov.se/determine-if-wordpress-ajax-request-is-a-backend-of-frontend-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
| /** | |
| * Determine whether ajax request from frontend. | |
| * | |
| * @return boolean | |
| */ | |
| function request_is_frontend_ajax() { | |
| $script_filename = isset($_SERVER['SCRIPT_FILENAME']) ? $_SERVER['SCRIPT_FILENAME'] : ''; | |
| //Try to figure out if frontend AJAX request... If we are DOING_AJAX; let's look closer | |
| if((defined('DOING_AJAX') && DOING_AJAX)) { | |
| //From wp-includes/functions.php, wp_get_referer() function. | |
| //Required to fix: https://core.trac.wordpress.org/ticket/25294 | |
| $ref = ''; | |
| if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) | |
| $ref = wp_unslash( $_REQUEST['_wp_http_referer'] ); | |
| elseif ( ! empty( $_SERVER['HTTP_REFERER'] ) ) | |
| $ref = wp_unslash( $_SERVER['HTTP_REFERER'] ); | |
| //If referer does not contain admin URL and we are using the admin-ajax.php endpoint, this is likely a frontend AJAX request | |
| if(((strpos($ref, admin_url()) === false) && (basename($script_filename) === 'admin-ajax.php'))) | |
| return true; | |
| } | |
| //If no checks triggered, we end up here - not an AJAX request. | |
| return false; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment