Wordpress - Are 'wp_ajax' and 'wp_ajax_nopriv' exclusive to authenticated and non-authenticated users?
Looking at the WordPress source code, I'd say that wp_ajax_nopriv_*
fires only if you're not logged in, and wp_ajax_*
fires otherwise.
Here's the relevant bit, in admin-ajax.php
, lines 85-115 in version 5.0.3:
if ( is_user_logged_in() ) {
// If no action is registered, return a Bad Request response.
if ( ! has_action( 'wp_ajax_' . $_REQUEST['action'] ) ) {
wp_die( '0', 400 );
}
/**
* Fires authenticated Ajax actions for logged-in users.
*
* The dynamic portion of the hook name, `$_REQUEST['action']`,
* refers to the name of the Ajax action callback being fired.
*
* @since 2.1.0
*/
do_action( 'wp_ajax_' . $_REQUEST['action'] );
} else {
// If no action is registered, return a Bad Request response.
if ( ! has_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] ) ) {
wp_die( '0', 400 );
}
/**
* Fires non-authenticated Ajax actions for logged-out users.
*
* The dynamic portion of the hook name, `$_REQUEST['action']`,
* refers to the name of the Ajax action callback being fired.
*
* @since 2.8.0
*/
do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );
}
So, if you're logged in (ie, is_user_logged_in()
is true
), it runs the wp_ajax_*
action(s), otherwise it runs the wp_ajax_nopriv_*
actions.
If you want the same action run regardless whether your user is logged in or not, I'd recommend you hook to both wp_ajax_*
and wp_ajax_nopriv_*
.
As per wp_ajax_(action)
codex:
This hook is functionally the same as
wp_ajax_(action)
, except the "nopriv" variant is used for handling AJAX requests from unauthenticated users, i.e. whenis_user_logged_in()
returns false.
is_user_logged_in()
determines whether the current visitor is a logged in user. It will return true
if user is logged in, false
if not logged in.