is_admin() and AJAX in WordPress

is_admin() is a quirky function, 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 documentation page:

Determines whether the current request is for an administrative interface page.

In other words, is_admin does not check whether the user is logged in.

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 wp_doing_ajax() function to check whether AJAX is being used.

Before:

if ( is_admin() ) {

After:

if ( is_admin() && ! wp_doing_ajax() ) {