ajax - Are 'wp_ajax' and 'wp_ajax_nopriv' exclusive to authenticated and non-authenticated users

admin2025-06-04  2

Basically what I'm asking is, is wp_ajax_nopriv exclusive to non-logged-in users?

Will a wp_ajax_nopriv action fire if a user is logged in?

Basically what I'm asking is, is wp_ajax_nopriv exclusive to non-logged-in users?

Will a wp_ajax_nopriv action fire if a user is logged in?

Share Improve this question edited Jan 23, 2019 at 9:31 fuxia 107k39 gold badges255 silver badges461 bronze badges asked Jan 22, 2019 at 22:18 SwenSwen 1,4047 gold badges22 silver badges37 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 9

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. when is_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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748983707a315379.html

最新回复(0)