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 inwp-admin/admin-ajax.php
. Some very weird plugins, like Jetpack, are defining that constant in unexpected places, so you might include a check foris_admin()
as well.Example:
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:
Good news, the function is there now.
Just to recap, the
admin-ajax.php
defines something like this.Fuxias solution returns
false
also for ajax request made from the admin panel. But these requests should returntrue
, because the data you are requesting is provided for an admin view. To solve this issue you can use the following function:DOING_AJAX
constant checks if you are inadmin-ajax.php