How to check if I am in admin-ajax.php?

Check the constant DOING_AJAX. Its definition is the first working code in wp-admin/admin-ajax.php. Some very weird plugins, like Jetpack, are defining that constant in unexpected places, so you might include a check for is_admin() as well.

Example:

if ( is_admin() && defined( 'DOING_AJAX' ) && DOING_AJAX )
{
    // do something
}

I have asked for a simpler way to check this a long time ago, and this was finally implemented in 4.7.0.

So for WP 4.7 and higher you can use:

if ( wp_doing_ajax() )
{
    // do something
}

Leave a Comment