WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 or in the frontend of the site. What is the best way to go about doing that?

share|improve this question
up vote 29 down vote accepted

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, but there doesn't seem to be much progress, so we have to live with this one for now.

share|improve this answer
3  
if ( defined( 'DOING_AJAX' ) ) is enough by itself. The constant is only set in admin-ajax.php so you don't need to check for a value. – John Reid Nov 26 '14 at 13:55
4  
@JohnReid It is a global constant, anyone can set it to any value, including FALSE. – toscho Nov 26 '14 at 16:36
    
Good point. There's nowhere in the WP core that sets this value but I suppose that it doesn't mean that some rogue plugin might not set it to false instead. A +1 for you, sir! – John Reid Dec 1 '14 at 10:32
    
It is the codex way, but in practice I saw people setting that flag in their theme, so this solution is good if you want to know if you should behave like it is ajax, but might not be best if you actually need to know if it is ajax request. – Mark Kaplun Mar 11 at 9:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.