Ajax Request for both logged and non logged users

As my understanding, The wp_ajax_{action} hook only fires for logged in users. For logged-out users, wp_ajax_nopriv_{action}action is triggered on an ajax request.

So, how can I write for both logged and non-logged users? Do I have to write two functions?

Eg Situation: There is a form which can be filled by both logged and non-logged users.

Answers 2

  • You can add the function to both hooks:

    add_action('wp_ajax_ajaxTest', 'ajaxTest');
    add_action('wp_ajax_nopriv_ajaxTest', 'ajaxTest');

    But, there's a better way to do it, use a REST API endpoint:

    add_action( 'rest_api_init', function () {
            register_rest_route( 'yourstuff/v1', '/test/', array(
                    'methods' => 'POST',
                    'callback' => 'yourstuff_test_endpoint'
            ) );
    } );
    function yourstuff_test_endpoint( $request ) {
        $stuff = $request['stuff'];
        return "Received ".esc_html( $stuff );

    Now if we flush our permalinks we'll find a new endpoint at example.com/wp-json/yourstuff/v1/test, and when we do a POST request to it, we get back a JSON string. E.g.

    jQuery.ajax( {
        url: '/wp-json/yourstuff/v1/test',
        method: 'POST',
            'stuff' : 'Hello World!'
    } ).done( function ( response ) {
        console.log( response );
    } );

    With that JavaScript I would expect to see the following in the console:

    "Received Hello World!"

    You can pass more parameters to register_rest_route telling it about what arguments your request expects/needs/are optional, authentication, validation, sanitisation, and it will take care of it all for you.

    With WP Admin AJAX, you have to do all of it yourself, and hope that you built it right, as well as program in all the possible errors. The REST API does that all for you

  • No. You have to write only one function. For example,

    function ajaxTest(){
    //your code
    add_action('wp_ajax_ajaxTest', 'ajaxTest');
    add_action('wp_ajax_nopriv_ajaxTest', 'ajaxTest');

Related Questions