在前端登录时将Wordpress用户重定向到他们自己的帖子

时间:2013-09-09 20:01:04

标签: php wordpress redirect login custom-post-type

我正在尝试让Wordpress的前端登录重定向到他们注册时自动创建的帖子(在自定义帖子类型中)。

我可以使用wp_query获取我想要重定向的URL。我想这不是最好的方法,但我不知道足够的PHP来解决它。这是我目前的尝试,但它只是打印一个空白页面上的网址(至少是右边的!),网页上已经有相同的登录网址:

function my_login_redirect( $redirect_to, $request, $user ){
    global $user, $post;
    $args = array(
       'author' => $current_user->ID,
       'post_type' => 'course-providers',
       'showposts' => 1,
       'caller_get_posts' => 1
    );
    $my_query = null;
    $my_query = new WP_Query($args);

    if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) : $my_query->the_post(); ?>
       <?php wp_redirect ( the_permalink () ); ?>
       <?php 
    endwhile;
    } else {
        echo "This User Has no Profile";
    }

}
add_filter("login_redirect", "my_login_redirect", 10, 3);

另外,我想我不需要wp_redirect而且我应该只使用login_redirect过滤器本身,但同样,我现在很丢失,只是在黑暗中拍摄很多镜头。

感谢您的帮助,如果有其他信息可以让其他人更有帮助或更容易回答,请告诉我。谢谢!

1 个答案:

答案 0 :(得分:0)

我最终使用模板重定向来完成这项工作。我认为从技术上讲,这是一种更好的方法,但它的加载速度非常快,并且正是我所需要的。

所以,现在,当用户登录时,会转到直接的url- / profiles - 而该页面上的模板只是一个重定向。我使用了这个smashing magazine post on random redirects中的想法和一些示例代码来实现它。

这是我在functions.php文件中使用的函数,用于使重定向发生的模板:

function profile_redirect() {
// This is a template redirect
// Whenever someone goes to /profile (or any page using the profile template)
// this function gets run

if ( is_user_logged_in() ) {
    global $current_user, $post;
    $args = array(
        'author' => $current_user->ID,
        'post_type' => 'profile',
        'posts_per_page' => 1
        );
    $my_query = null;
    $my_query = new WP_Query($args);

    if( $my_query->have_posts() ) {
        while ( $my_query->have_posts() )
            $my_query->the_post();
            //We have a post! Send them to their profile post.
            wp_redirect ( get_permalink () );
        exit;
    } else {
        // If there are no posts, send them to the homepage
        wp_redirect ( get_bloginfo('url') );
        exit;
    }
    wp_reset_query();
} else {
    // If they're not logged in, send them to the homepage
    wp_redirect ( get_bloginfo('url') );
    exit;
}

}

然后,在我的个人资料模板上,我把它放在顶部,打开php标签来运行该功能:

profile_redirect(); ?>

这对我有用,所以我暂时保留原样:)

相关问题