0

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?

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.com/bueltge/authenticator
    – bueltge
    Sep 3, 2020 at 13:32

1 Answer 1

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?

1
  • Sure, I believe that identify the page by its ID would make the job perfectly. It'll be the only and unique private page Sep 4, 2020 at 6:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.