如果用户从某个页面登录,如何在登录后重定向?

时间:2016-03-24 08:31:38

标签: php wordpress

我在使用WordPress,我正在尝试在登录后重定向用户,但前提是他们从某个页面登录(slug是'upgrade-now-gold-class-coaching')

这是我到目前为止所做的:

function my_login_redirect( $redirect_to, $request, $user ) {
    //did they try to login from this page?
    if ( $request == "upgrade-now-gold-class-coaching" ) {
        //is there a user to check?
        if ( isset( $user->roles ) && is_array( $user->roles ) ) {
            //check for admins
            if ( in_array( 'administrator', $user->roles ) ) {
                // redirect them to the default place
                return $redirect_to;
            } else {
                return "https://www.drewbairdfitness.com/11674-2/";
            }
        } else {
            return $redirect_to;
        }
    } else  {
        return $redirect_to;
    }
}

add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );

谢谢!

1 个答案:

答案 0 :(得分:0)

@Jared Codling ,点击login_redirect提前重定向,您可以使用wp_safe_redirect。这里有一些示例方法重定向,如果请求从某个页面登录到另一个页面,并且用户角色不是administrator

重定向到网页使用其网址:

add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );

function my_login_redirect( $redirect_to, $request, $user )
{
    /* target certain page with their part url
     * you can use url_to_postid( $request )
     * and pass in conditional statement with your target post id
     * target post/page id = 7
     * if ( 7 == url_to_postid( $request ) )
     * make it sure you have hidden input name redirect_to
    */
    if ( false !== strpos( $request, 'upgrade-now-gold-class-coaching' )
        && ! empty( $user->roles ) )
    {
        /* exclude administrator as role
         *  
        */
        if ( is_array( $user->roles )
            && ! in_array( 'administrator', $user->roles ) )
        {
            /* redirect to another url
             * we use hardcode slug
            */
            $redirect_to = home_url( '/11674-2/' );
            wp_safe_redirect( $redirect_to, 302 );
            exit;
        }
    }
    return $redirect_to;
}

重定向到网页使用其ID:

add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );

function my_login_redirect( $redirect_to, $request, $user )
{
    /* target certain page with their part url */
    if ( false !== strpos( $request, 'upgrade-now-gold-class-coaching' )
        && ! empty( $user->roles ) )
    {
        /* exclude administrator as role
         *  
        */
        if ( is_array( $user->roles )
            && ! in_array( 'administrator', $user->roles ) )
        {
            /* redirect to another url
             * you can use function get_page_link(40), mean page id 40
            */
            $redirect_to = get_page_link(40);
            wp_safe_redirect( $redirect_to, 302 );
            exit;
        }
    }
    return $redirect_to;
}

注意:通过防火过滤功能login_redirect并使用自定义登录表单,只需确保隐藏输入名称redirect_to,例如{中的默认wp登录表单{1}}。

相关问题