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:

Read More
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?

Related posts

Leave a Reply

2 comments

  1. 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))

  2. Why not make your users contributors instead of subscribers? By default, contributors can submit draft posts but not publish, plus the AJAX function will work.

    If you don’t want contributors accessing the dashboard, you can keep them out with this snippet:

    function wpse_77140_restrict_admin() {
        if ( ! current_user_can( 'publish_posts' ) )
            wp_redirect( home_url() );
    }
    
    add_action( 'admin_init', 'wpse_77140_restrict_admin' );