在(自定义)登录后重定向到请求的页面

时间:2012-06-28 作者:parantox

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.

1 个回复
SO网友:Pontus Abrahamsson

将此代码段添加到函数中。wordpress主题的php会将访问者重定向到他们登录后查看的页面。

  if ( (isset($_GET[\'action\']) && $_GET[\'action\'] != \'logout\') || (isset($_POST[\'login_location\']) && !empty($_POST[\'login_location\'])) ) {
            function my_login_redirect() {
               $location = $_SERVER[\'HTTP_REFERER\'];
               wp_safe_redirect($location);
               exit();
            }
            add_filter(\'login_redirect\', \'my_login_redirect\', 10, 3);
    }

结束

相关推荐

Logout redirects to /forums/

不久前,我安装了一个插件,在注销时,它会将用户重新定向到/forums/.不幸的是,我不知道那是哪个插件,也不知道它是否仍然处于活动/安装状态。我可以查找哪些代码/数据库设置来删除有问题的代码?提前感谢,