How can visitors redirect wp-admin to the homepage?
My site details: 1. I used BuddyPress; 2. Users can sign up and login via BuddyPress; 3. User role only Admin and Author;
Needs: 1. wp-admin only admin can access, if not an admin, and visitors and Authors then redirect to home page; 2. Users force use BuddyPress login page.
Anyone have ideas?
How can visitors redirect wp-admin to the homepage?
My site details: 1. I used BuddyPress; 2. Users can sign up and login via BuddyPress; 3. User role only Admin and Author;
Needs: 1. wp-admin only admin can access, if not an admin, and visitors and Authors then redirect to home page; 2. Users force use BuddyPress login page.
Anyone have ideas?
The codex entry for the admin_init
hook has an example showing you how to do this.
/**
* Restrict access to the administration screens.
*
* Only administrators will be allowed to access the admin screens,
* all other users will be automatically redirected to
* 'example/path/to/location' 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_safe_redirect( 'example/path/to/location' ); // Replace this with the URL to redirect to.
exit;
}
}
add_action( 'admin_init', 'restrict_admin_with_redirect', 1 );
A few notes on how this works:
current_user_can( 'manage_options' )
checks to see if the logged in user has a capability only admin accounts should have. The proceeding !
means "not". We are checking for a capability instead of simply checking for the admin role as a best practice. You should treat the role as nothing more than a label and check for capabilities (read: permissions) to check if a user can do something. Read more about the roles & caps here.wp_doing_ajax()
Makes sure the current request is not a WordPress Ajax request. If it is, it's possible the user is not actually on the admin so no need to redirect. The proceeding !
means "not".wp_safe_redirect( 'example/path/to/location' );
Redirects the user to the URL you pass it. You can find the documentation here. Note: wp_safe_redirect()
is the recommended function not wp_redirect()
. Thanks @Nathan Johnson
exit;
Stops execution of the script making the redirect the last action we do.add_action( 'admin_init', 'restrict_admin_with_redirect', 1 );
Fire this check on the admin_init
because it's the first hook fired after authentication. Pass 1
as the last argument to make sure out function is fired before any other hooks.Is your own internet connection on a static IP? If so you can block wp-admin to everyone except your own IP. This is what I do. It can be achieved via various plugins but can also be done via htaccess.