How to redirect non-logged users requesting for a specific page/URL to another page/URL and display a message like “for members only”. I know its quite easy to code using !is_user_logged_in() function but i don’t know how to code it because i am a newbie to WordPress. Care to tell me the file to put the code also.
5 comments
Comments are closed.
Here are 2 examples which you will need to modify slightly to get it working for your specific needs.
Put this in your child theme functions file, change the page ID or slug and the redirect url.
You could also use code like this:
You can add the message directly to the page or if you want to display the message for all non logged in users, add it to the code.
http://codex.wordpress.org/Function_Reference/wp_redirect
This would be better:
What this does is redirect the user to the login page. Once logged in, the user is redirected back to the secure page they were trying to access initially.
Documentation here:
https://codex.wordpress.org/Function_Reference/auth_redirect
How can we tell you where to put it if you didn’t tell us what and where you want to display it? Whole posts? Pages? Custom parts of pages? Sorry… I guess my crystal ball isn’t quite working today.
Since you are, and I quote you: “a newbie to wordpress” you should rather learn, than to ask for direct answer.
As for where you should read the reference 1 link. This will tell you which file you need to put it in.
As for how to do it you should first read reference link 2 and 3.
Overall it should look something like this:
Of course the above code needs to go into a loop. You can build it up as complex or as simple as you want. For example instead of simple text if not logged in you can display whole sign up form for example or – as I would suggest – a divided screen where user can log in (since user can have an account but forgot to sign in) or sign up (if he doesn’t have one).
Added after comments below:
To redirect use
header
with thewp_login_url
– again, check references 1 and 2 below:Reference:
You can’t redirect to a specific page, but every non-logged-in user will be redirected to Log-In Screen.
WordPress Reference:
auth_redirect()
Just to mention another solution.
According to this guide:
https://vvcares.com/blog/post/wordpress-buddypress-hide-page-from-non-members
How to hiding members page from non logged in users ?
Here the simple step to protect your WordPress BuddyPress member only pages. Add this simple snippet into your theme’s ‘functions.php’ file. That’s it..
The below snippet sample will redirect the visitor if the visitor is not logged in & trying to visit the sensitive BuddyPress pages.
Will redirect non-logged-in users trying to access private content to your front page or home page