→ is_admin() and AJAX in WordPress

is_admin() is one of the quirkiest WordPress functions, and its accidental mis-use can cause issues with AJAX-based plugins.

The Problem

Many developers assume that is_admin() will return TRUE only when a user is logged into the admin area, but that isn’t the case. According to the codex page:

This is a boolean function that will return TRUE if the URL being accessed is in the admin section, or FALSE for a front-end page.

In other words, only the URL is checked (not whether the user is logged in).

If a plugin incorrectly handles is_admin() for AJAX requests, then the necessary code may not get loaded properly.

AJAX Requests

When a plugin makes a WordPress AJAX request, it uses /wp-admin/admin-ajax.php. This is technically an admin page, so is_admin() returns TRUE, even for front-end requests.

The Solution

Use the DOING_AJAX constant to check whether AJAX is being used.

Before:

if ( is_admin() ) {

After:

if ( is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {