Using Using defined(‘DOING_AJAX’)! I’m really noting this for my own use, I could not remember it for a while there. Was searching for a function and would never have guessed it could be a constant. Obviously when an Ajax request is made, headers are loaded and so a constant can be defined. I must try to remember, if not I’ll find this page in a Google…I hope.
That simple really. If “DOING_AJAX” has been set it tells us that an Ajax request is happening. During this the WordPress header is loaded and hooks like “init” will be triggered. You may want that to happen but in many cases you will not, especially if the function results in output.
A simple use is, if defined DOING_AJAX return false. Come straight out of the function being hooked as quick as possible. You might think, well why not prevent an action happening at all, prevent this line “add_action(‘init’, ‘wtgcsv_event_check’);” actually being called when DOING_AJAX is set. We can’t do that. Well in some scenarios I think it would be possible and have an effect but it is not recommended. Arguments of any kind should be done within the add_action function.
There is also ways to do something similar using “remove_action”. How I find this best suited when I’m running a function that uses a WordPress function or object which then triggers an action. So in other words avoided an action running when it’s purpose event happens. The action might not be suitable for the event happening when your plugin or theme is doing and the action exists for when it happens naturally. I hope that makes some sense, if not but you feel it’s in the area your learning about just let me know. The scenario I have in mind is my plugin that updates posts and I also have an add_action for when visitors update posts. I don’t want the add_action to be triggered when my admin trigger post updating using my plugin.