Quick Tip: Keeping Users Out of the Admin Area

Every once in a while, you may have a need to keep specific user roles out of the administrative dashboard, more than likely to simply keep them from getting confused by the design differences between the front-end and the back-end. Doing so is fairly simple, but there’s one item you have to watch out for. When any AJAX requests are made against WordPress (at least, when done correctly), they run through admin-ajax.php, which is part of the administrative backend. As a result, the is_admin() conditional function returns `true`, and the admin_init() action is fired. Therefore, in order to make sure that AJAX requests work for everyone, we need to first check to see if this is an AJAX request or not.

The code you’d use to keep Subscribers out of the administrative back-end might look something like the following Gist:

You can easily modify the default `$level` argument to look at a different capability if you want to block more users from getting to the back-end. You can also easily edit the address to which they’re redirected.

In the actual plugin where I’m using this code, I’ve set up options in the administrative area allowing administrators to choose which levels of users they want to keep out of the admin area, and I’ve allowed them to choose a specific page on the site to which those users will be redirected.

Leave a Reply