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