Allow AJAX call to other roles than admin

On my website, registered users (subscriber role) can send drafts and, if admins validate them, they are published.

I’m trying to add a tag box to frontend editor used to send new posts. To implement the autocomplete feature I’m making an AJAX call to this URL:

http://example.com/wp-admin/admin-ajax.php?action=ajax-tag-search&tax=post_tag

That works great for an administrator user, but it doesn’t work for subscribers. Does anyone know any way to achieve this without calling to admin-ajax.php?

2 Answers
2

All the WordPress AJAX calls should be handled by the admin-ajax.php, wether they happen on the frontend or in the backend. To grant the access you have to register the callbackfuntion for the AJAX call add those lines to your file:

add_action( 'wp_ajax_prefix_update_post', 'prefix_update_post' );
add_action( 'wp_ajax_nopriv_prefix_update_post', 'prefix_update_post' );

Be sure to add some validation in the prefix_update_post function, as a non loggedin user should not be allowed to send the draft.

So this line should do the trick:

function prefix_update_post() {

    if ( current_user_can( 'edit_post' ) ) {

        // your goodies here

    }

}

If everything works out fine, perfect, else you may have to send the userID with the AJAX call and check if the User has the correct permissions (get_user_by('id', $userid))

Leave a Comment