How can I prevent access to /wp-admin and wp-login.php for all members?

Hello,
I would like to prevent all access to /wp-admin and wp-login.php for ALL non admin members. I'd also like to give members the ability to login/logout via the Membership login widget.

Ideally, if someone (non admin) tries to access /wp-admin or wp-login it would just redirect to a /login page which allows them to log in or out.

I've seen this done before, I just need some guidance on where to do it.

Thanks very much,

Ryan

  • Kingdom Studios
    • The Bug Hunter

    Hey @Ryan,

    Question: If the user hasn't logged in yet, how would it be known if the user was an admin or not?

    Have you tried the Better WP Security plugin? Make sure you have a good backup before using it, but it provides suggestions for improved security. One of which is a way to hide the admin area.

    Let me know what you think.

    Regards,

    Martin

  • Ryan
    • WPMU DEV Initiate

    Thanks Jack and Martin for your responses.

    Martin - I'm using a frontend login form (which uses ajax to validate) to allow users to login/register. /wp-admin should be available to administrators once logged in, otherwise they should be redirected to a frontend /account page.

    Jack, the code you provided works well except it doesn't allow my ajax form to validate; it just does nothing when the form is submitted thus preventing any users from logging in. I've since removed the function from functions.php to keep it working. Any suggestions?

  • Ryan
    • WPMU DEV Initiate

    Ok, I got it figured out. I needed to add () around the ajax check as follows. Works like a charm!

    add_action( 'admin_init', 'redirect_non_admin_users' );
    /**
     * Redirect non-admin users to home page
     *
     * This function is attached to the 'admin_init' action hook.
     */
    function redirect_non_admin_users() {
    	if ( ! current_user_can( 'manage_options' ) && ('/wp-admin/admin-ajax.php' != $_SERVER['PHP_SELF']) ) {
    		wp_redirect( home_url() );
    		exit;
    	}
    }

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.