I am developing a WP site locally and I want the content to be viewable only to users that have logged in, except for the front page that's visible to everyone.
When a non-logged in user clicks on a link from the front page, it takes him to a customized login page made with Theme My Login. If he logins succesfuly from there, I want him taken to the page he initially requested, i.e. the link he clicked while at the front page.
I have the first part of this working. Non-logged in users are taken to the custom login page. I cannot find a way to send them directly where they wanted to go, though. I have read several things and posts on the matter, tried different plugins, but haven't managed to apply them to my case.
This is the code I am using to send them to the login page:
function checkLogged()
{
$pg = get_permalink();
if (!is_user_logged_in() && !is_front_page() && $pg != home_url('/?page_id=126'))
{
wp_redirect(home_url('/?page_id=126'));
exit;
}
}
add_action('wp_head', 'checkLogged');
where the page with ID=126 is the custom login page.
Right now I am redirecting to the front page after login. But I want to change that to the requested page. I am using the login_redirect filter for that.
function takeMeThere()
{
$lastPage = wp_get_referer();
$loginPage = home_url('/?page_id=126');
if ($lastPage == $loginPage)
{
wp_redirect(home_url()); //this redirection should be to the requested page
exit;
}
}
add_filter('login_redirect', 'takeMeThere', 10, 3);
I don't know if some of the code in the latter function is redundant but the login page kind of breaks without that (the footer doesn't appear). Anyway, essentially I'm asking how I can somehow retrieve the url of the link the user clicked on when not logged in. Or if there's an alternative approach I'd be happy to try it but I want that custom login page, not the Wordpress one.
Any help would be greatly appreciated.