Menu

Block Access to wp-admin and WordPress Dashboard

There is a couple of reasons why you would want to ban access to wp-admin folder or WordPress dashboard in general for regular users. Some websites allow commenting only for registered users but after the user is signed on he can access the WordPress dashboard. Granted, there's not much he can do there if his role is Subscriber, but you might want to prevent access nonetheless.

Basic WordPress user redirection

Most articles on this topic encourages the technique of detecting when someone other than admin tries to access wp-admin folder and just redirects him to the front page. This seems fine but it has one major drawback: AJAX powered plugins (pools, contact forms, etc) won't work because your are banning the access to admin-ajax.php WordPress file which handles those requests. Don't let the "admin" part of the file name fool you, it's also used for handling the requests coming from the frontend. Also, members that have Editor rights won't be able to write articles.

So what's the solution? Allow the visitor to send POST data only to admin-ajax.php file and ban everything else directed to wp-admin folder and wp-login.php. Check out the code below and just place it inside of your theme's functions.php.

Blocking the dashboard but allowing login page

Code below will allow the users to access only the default WordPress login page, once signed in they will not be able to see the dashboard.

functions.php
function block_dashboard() {
    $file = basename($_SERVER['PHP_SELF']);
    if (is_user_logged_in() && is_admin() && !current_user_can('edit_posts') && $file != 'admin-ajax.php'){
        wp_redirect( home_url() );
        exit();
    }
}

add_action('init', 'block_dashboard');

Using conditional tag is_user_logged_in() we are allowing the access to the login page. Once the user is logged in he won't be able to access the wp-admin section again. You might want to add a logout link somewhere on your website so the user can end his session.

header.php
if(is_user_logged_in()) {
    <a href="<?php echo wp_logout_url( home_url() ); ?>">Logout</a>
}

Completely blocking the login page and dashboard

If you have a frontend login system then blocking the default WordPress login page, together with the dashboard, might come in handy.

functions.php
function block_wpadmin() {
    $file = basename($_SERVER['PHP_SELF']);
    if ($file == 'wp-login.php' || is_admin() && !current_user_can('edit_posts') && $file != 'admin-ajax.php'){
        wp_redirect( home_url() );
        exit();
    }
}

add_action('init', 'block_wpadmin');

That's it! Any plugin using AJAX will function as it should and your dashboard is only accessible to your staff and yourself.