Blog

Only Allow Administrators Access to Admin Area

For many WordPress developers, building a website where there is only a content producer who is going to access the Admin area of WordPress is fairly easy.  You know before hand which users will have access and you can prepare and lock down the site accordingly.  The “fun” begins with you begin allowing visitors / users / customers / clients to register for accounts on the WordPress site.

That’s when THIS begins to happen for users…

Why should your subscribers even be allowed to see the “underbelly” of WordPress (as described by my older neighbor).  Yes, you probably want to offer the ability to update profile information for subscribers, but most developers are going to do that on the front end of the site, in an area that is much easier to style.  And while most “front end user profile” WordPress plugins may redirect logged in users to their new better looking profile/account pages, many of them don’t block access to the Admin area.

[edd_restrict id=”279,327,3218″ message=”The additional content, code snippets, and enhanced discussions are only available to members of the WPStudio Community.“]

This where the good stuff happens.  The following code does two things.  It first checks to make sure the current user is NOT an Administrator and checks to see if that current user is trying to access any of the Admin pages in WordPress (essentially the /wp-admin/ folder).  If the code decides you shouldn’t have access it simply redirects the page load to go to the homepage.

function wps_redirect_non_admin_users(){
    if ( !current_user_can('manage_options') && '/wp-admin/admin-ajax.php' != $_SERVER['PHP_SELF'] ){
        wp_redirect(home_url());
        exit;
    }
}
add_action('admin_init', 'wps_redirect_non_admin_users');

You can adjust the “location” of the redirection by changing the home_url() to a different URL.

This is an excellent code snippet to save and/or use for all your sites that you are working to “lock down” and protect your users from having access to the admin areas of WordPress.

[/edd_restrict]


Subscribe for Updates and Special Deals




Marketing permission: I give my consent to to be in touch with me via email using the information I have provided in this form for the purpose of news, updates and marketing.


  1. Great Idea BB. This is something that seems to be coming up quite a bit lately. It is important to constantly add layers to Your WordPress Security, and this will be a nice additional to anyones tool box.

    Thanks,
    Ryan Sharrer

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.