I added this to my functions.php to restrict non-admin access to wp-admin by redirecting the non-admin to the home page. However, this does not work for users who aren't users (users who are not logged in).
How can I include visitors who are not users in this script?
/**
* Restrict access to the administration screens.
*
* Only administrators will be allowed to access the admin screens,
* all other users will be automatically redirected to the front of
* the site instead.
*
* We do allow access for Ajax requests though, since these may be
* initiated from the front end of the site by non-admin users.
*/
function restrict_admin_with_redirect() {
if ( ! current_user_can( 'manage_options' ) && ( ! wp_doing_ajax() ) ) {
wp_redirect( site_url() );
exit;
}
}
add_action( 'admin_init', 'restrict_admin_with_redirect', 1 );
FYI: I created a custom log-in form on a page other than wp-admin so this will not lock out admin
EDIT 2: this is in the functions.php file which may be complicating the issue since when a non-user accesses wp-admin, the server is treating that access as a failed log-in attempt and redirecting the user to the "access-denied" page and not a 404
/**
* Redirect user on invalid log-in attempts
*/
function login_failed() {
$login_page = home_url( '/access-denied' );
wp_redirect( $login_page . '?login=failed' );
exit;
}
add_action( 'wp_login_failed', 'login_failed' );
function verify_username_password( $user, $username, $password ) {
$login_page = home_url( '/access-denied' );
if( $username == "" || $password == "" ) {
wp_redirect( $login_page . "?login=empty" );
exit;
}
}
add_filter( 'authenticate', 'verify_username_password', 1, 3);
is_user_logged_in()
to check if the user is signed in or if he is just a guest.