Right now for my plugin, I am using in_admin()
to determine if the user is in the frontend of the site or in the admin area. However, the problem occurs when plugins use admin-ajax.php
to process ajax requests.
I need a way to register hooks and plugins only when processing admin-ajax.php
file or in the frontend of the site. What is the best way to go about doing that?
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
}