I am a novice with php, so I need help with this one. Please bear with me.
I want to include an error message on the wp_login.php page when visitors are redirected from a “user only/logged in” page. Below is the code I have for the page template which I use for “users only.” It checks if the user is logged in or not. if he is not, he is redirected to the login page. This is where I get stuck. I tried to but together some code I found on google but no luck. Is there a way to pass an error message from here to the login page?
if (!is_user_logged_in()) { auth_redirect(); }
add_action('login_head','ref_access');
function ref_access() {
global $error;
if( !empty($_GET['ref']) && 'access' == $_GET['ref'] )
$error = 'Restricted area, please login to continue.';}
Any code suggestions would be appreciated.
The thing here is that you keep all code in your template file, which will prevent some of it from executing. Once you load your template without being logged in
auth_redirect()
will be run. This function stops the page loading and redirects to the login page, thus yourlogin_head
callback will never be called. Try dividing your code like this:your-template.php
functions.php
While this will make
ref_access
execute onlogin_head
it also means that it will run each time the login page is displayed. To account for this, you will have to find a way to let WordPress keep track of when and from whereauth_redirect()
is being called, and makeref_access()
check for some kind of referrer. The first thing that comes to mind is using sessions to store information about each ongoing redirection and clear the session data inref_access()
or on each new page load as needed.An alternative option is using the
login_message
filter to display messages on the log in page, but the redirect/referrer issues applies there as well. Here’s an example: