Check if request is made from WordPress backend

It is not so easy to check if a request was made from the backend or not. This post shows my solution for that, which I build recently.

The problem with is_admin()

The plugin Lazy Loading Responsive Images needs to check if a request was made in the backend, to modify only image markup at the front end. The function is_admin() checks if a backend page was called – this was the first solution used in the plugin.

But then a user came across a problem with that: the function returns true for AJAX requests because they use the wp-admin/admin-ajax.php. That means the lazy loading plugin did not work for front end content which is added via AJAX because is_admin() returns true.

The solution

With that in mind, the solution has to check for AJAX requests somewhere. The first try of a function to replace the is_admin() calls looked like the following (kindly directly supplied by the user zitrusblau with the issue report):

<?php
function is_admin_request() {
	if ( function_exists( 'wp_doing_ajax' ) ) {
		return is_admin() && ! wp_doing_ajax();
	} else {
		return is_admin() && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX );
	}
}

That worked for the front end, but the same user later found a new issue with that: the plugin now lazy loads the post thumbnail feature in the backend. With that, a newly chosen featured image did not show up in the meta box directly, but only after saving the post.

This is the current solution:

<?php
/**
 * Check if this is a request at the backend.
 *
 * @return bool true if is admin request, otherwise false.
 */
function is_admin_request() {
	/**
	 * Get current URL.
	 *
	 * @link https://wordpress.stackexchange.com/a/126534
	 */
	$current_url = home_url( add_query_arg( null, null ) );

	/**
	 * Get admin URL and referrer.
	 *
	 * @link https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/pluggable.php#L1076
	 */
	$admin_url = strtolower( admin_url() );
	$referrer  = strtolower( wp_get_referer() );

	/**
	 * Check if this is a admin request. If true, it
	 * could also be a AJAX request from the frontend.
	 */
	if ( 0 === strpos( $current_url, $admin_url ) ) {
		/**
		 * Check if the user comes from a admin page.
		 */
		if ( 0 === strpos( $referrer, $admin_url ) ) {
			return true;
		} else {
			/**
			 * Check for AJAX requests.
			 *
			 * @link https://gist.github.com/zitrusblau/58124d4b2c56d06b070573a99f33b9ed#file-lazy-load-responsive-images-php-L193
			 */
			if ( function_exists( 'wp_doing_ajax' ) ) {
				return ! wp_doing_ajax();
			} else {
				return ! ( defined( 'DOING_AJAX' ) && DOING_AJAX );
			}
		}
	} else {
		return false;
	}
}

If you know a better solution, please share it with me 🙂

Related posts

Leave a Comment

Your email address will not be published. Required fields are marked *