wp_doing_ajax()WP 4.7.0

Determines whether the current request is a WordPress Ajax request.

This function is a wrapper for:

defined( 'DOING_AJAX' ) && DOING_AJAX
1 time — 0.000007 sec (speed of light) | 50000 times — 0.01 sec (speed of light) | PHP 7.0.8, WP 4.7
Hooks from the function

Return

true|false. True if it's a WordPress Ajax request, false otherwise.

Usage

if( wp_doing_ajax() ){
	// this is AJAX request
}

Examples

0

#1 Differentiate output behavior based on how it is being called

In a PHP code, if we want to differentiate its output behavior based on how it is being called (like a normal function or like a WP AJAX callback), then we should use the wp_doing_ajax() function like below:

function wpdocs_render() {

	// SOME LOGIC ...

	$return_data = array( 'success'  => true );

	if ( wp_doing_ajax() ) {
		wp_send_json_success( $return_data );
	}
	else {
		return $return_data;
	}

}
-1

#2 Do something if the current request is an AJAX request

Add AJAX hooks only for AJAX request.

if( wp_doing_ajax() ){

	add_action( 'wp_ajax_myaction',        'ajax_handler' );
	add_action( 'wp_ajax_nopriv_myaction', 'ajax_handler' );

	function ajax_handler(){
		// ajax request handler
	}
}

Changelog

Since 4.7.0 Introduced.

wp_doing_ajax() code WP 6.5.2

function wp_doing_ajax() {
	/**
	 * Filters whether the current request is a WordPress Ajax request.
	 *
	 * @since 4.7.0
	 *
	 * @param bool $wp_doing_ajax Whether the current request is a WordPress Ajax request.
	 */
	return apply_filters( 'wp_doing_ajax', defined( 'DOING_AJAX' ) && DOING_AJAX );
}