admin管理员组

文章数量:1323336

I have a Wordpress page that should only be visible to the admin. Any other kind of user role, or logged-out visitors, should be redirected away to the home page if they ever try to visit that page.

Most snippets I found are good for redirecting after logging in or even redirect based on user role. Since I do not have registration on my website, there are no roles basically, just visitors and admin.

Any idea or where to look?

I have a Wordpress page that should only be visible to the admin. Any other kind of user role, or logged-out visitors, should be redirected away to the home page if they ever try to visit that page.

Most snippets I found are good for redirecting after logging in or even redirect based on user role. Since I do not have registration on my website, there are no roles basically, just visitors and admin.

Any idea or where to look?

Share Improve this question edited Sep 3, 2020 at 21:00 fuxia 107k38 gold badges255 silver badges459 bronze badges asked Sep 3, 2020 at 13:06 Paolo MontaltoPaolo Montalto 371 gold badge1 silver badge6 bronze badges 1
  • Look at the plugin 'Authenticator', I mean that should solve this goal. If you do not use a plugin, look at this code, it is OSS - github/bueltge/authenticator – bueltge Commented Sep 3, 2020 at 13:32
Add a comment  | 

1 Answer 1

Reset to default 1

The basic principles of this are easy enough, but how to implement it in your case is hard to say without knowing more.

if ( !is_user_logged_in() ) {
    auth_redirect();
}

Would redirect a non-logged in user to the login page

if (current_user_can('administrator'))

Would be used to identify whether someone had the admin role.

How to implement this is another matter. I recently made a custom page template for logged in users only to view data and I simply placed the first section of code above at the top of the template, with the rest of the page code in the 'else' statement. This could be extended further to identify if the user was also an Admin. However, you could also use an action hook to do this without using a custom page by applying the logic to a specific page ID or slug. Something like this.

The above might be enough to help you but if not, post a little more detail in your question. Specifically, how do you identify this particular page? By ID/Slug or have you created a template?

本文标签: Redirect away from page if user is not admin