Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

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 your login_head callback will never be called. Try dividing your code like this:

your-template.php

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

functions.php

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.';
}

While this will make ref_access execute on login_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 where auth_redirect() is being called, and make ref_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 in ref_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:

add_filter('login_message', 'wpse_87333_login_message');
function wpse_87333_login_message($messages) {
    $messages = 'Restricted area, please login to continue.';
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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