-1

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.

  • 1
    You can hook the same function to multiple hooks. This is how it would be written in most of the available examples, including the codex codex.wordpress.org/… – Jacob Peattie Jun 7 at 12:03
  • I see you're using the old WP Admin AJAX system, have you looked into using the newer REST API endpoints instead? They're a lot easier to work with and when you get things wrong it tells you so and why, instead of giving cryptic empty responses – Tom J Nowell Jun 7 at 13:01
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',
    data:{
        '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

1

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');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.