0

I have build a function to fetch a post in Wordpress served over ajax.

$.ajax({
        url: '/wp-admin/admin-ajax.php',
        type: 'POST',
        cache: false,
        data: {
          action: 'get_post_info',
          postId: postId,
        },
        success: function(data){


      });

In order to make it work if the user is not logged in, I have used wp_ajax_nopriv. But when the user is logged in now, the functionality crashes.

add_action('wp_ajax_nopriv_get_post_info', 'get_post_info');
function get_post_info(){
}

Is there a function like wp_ajax that work for both logged_in and not logged_in users?

  • It is best practice to declare a ajaxurl variable for non administration side usage. On the administration side ajaxurl is defined, see note here. – Nicolai Feb 7 '18 at 21:48
2

As it is said in the codex The wp_ajax_nopriv hook will not fire for authenticated users, i.e. when is_user_logged_in() returns true. To handle both unauthenticated and authenticated users, also use wp_ajax_(action).

2
add_action('wp_ajax_get_post_info', 'get_post_info');
add_action('wp_ajax_nopriv_get_post_info', 'get_post_info');

wp_ajax_nopriv_(action) only on front-end and only for non logged users. Use wp_ajax_(action) for logged in users.

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.