最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

plugins - Redirection of users away from wp-admin (but not administrators)

programmeradmin1浏览0评论

I want to redirect all users except the admin away from the wp-admin page.
If the logged in user tries to access /wp-admin then they will be redirected back home.
Right now they get a page that says "Sorry you are not allowed to access this page"
Can y'all please help me construct a function in my functions.php file to check for these conditions and redirect?
This is what I have, and it isn't working for what I want.

function acme_login_redirect( $redirect_to, $request, $user  ) {
  return ( is_array( $user->roles ) && in_array( 'administrator', $user->roles ) ) ? admin_url() : site_url();
}
add_filter( 'login_redirect', 'acme_login_redirect', 10, 3 );

I want to redirect all users except the admin away from the wp-admin page.
If the logged in user tries to access /wp-admin then they will be redirected back home.
Right now they get a page that says "Sorry you are not allowed to access this page"
Can y'all please help me construct a function in my functions.php file to check for these conditions and redirect?
This is what I have, and it isn't working for what I want.

function acme_login_redirect( $redirect_to, $request, $user  ) {
  return ( is_array( $user->roles ) && in_array( 'administrator', $user->roles ) ) ? admin_url() : site_url();
}
add_filter( 'login_redirect', 'acme_login_redirect', 10, 3 );
Share Improve this question edited Jan 26, 2022 at 15:43 Buttered_Toast 2,8191 gold badge8 silver badges21 bronze badges asked Jan 26, 2022 at 14:53 Jed BoothJed Booth 133 bronze badges 1
  • note that if this filter worked it would redirect non-admins on login but there is nothing to prevent users from just visiting WP Admin after they're already logged in – Tom J Nowell Commented Jan 26, 2022 at 15:57
Add a comment  | 

1 Answer 1

Reset to default 1

Here's how I do this:

// if admin send them to the dashboard, otherwise leave them on the frontend
add_action('wp_login', 'rt_login_redirect', 10, 2);  //use this action if you want them to be redirected only after login but leave the ability to to to the dashboard later (ie changing profile or pw).
add_action( 'admin_init', 'rt_login_redirect' ); // use this action to completely dis-allow all others besides the admin to access the dashboard.
function rt_login_redirect($user_login, $user) {

    if  (!current_user_can('manage_options')) {
            wp_safe_redirect( home_url(), 302);
            exit();
    }
}

The main function checks if the users is an admin by checking if the users has the ability to manage options. If they don't have that capability then the function will redirect them to the homepage. If they do they can stay on the backend.

The function is activated when someone try to take an action (as commented above) (chose an option based on what you want)

发布评论

评论列表(0)

  1. 暂无评论