我正在尝试在登录后将用户重定向到特定帖子。此帖子是自定义帖子类型的最新帖子,作者是当前登录的用户。
我目前必须使用以下代码才能获取特定的帖子url:
function member_permalink () {
$user_id = get_current_user_id();
$args=array(
\'post_type\' => \'cursist\',
\'author\' => $user_id
);
$current_user_posts = get_posts( $args );
$post_link = get_permalink( $current_user_posts->ID );
return $post_link;
}
以及登录后重定向用户的代码(摘自Codex)
function my_login_redirect( $redirect_to, $request, $user ) {
//is there a user to check?
if (isset($user->roles) && is_array($user->roles)) {
//check for subscribers
if (in_array(\'subscriber\', $user->roles)) {
// redirect them to another URL, in this case, the homepage
$redirect_to = member_permalink();
}
}
return $redirect_to;
}
add_filter( \'login_redirect\', \'my_login_redirect\', 10, 3 );
然而,我被重定向到WP管理员而不是帖子。
如果我对函数执行var\\u转储以获取特定的帖子url,那么我会得到以下结果(这是我想要的数据):
string(52) "http://example.com/cpt-slug/niels-pilon/"
我可能做错了什么,但不知道是什么。
最合适的回答,由SO网友:Iceable 整理而成
你应该通过$user 作为参数member_permalink() 而不是依赖get_current_user_id().
关于login_redirect 过滤器:
运行此筛选器时,$current\\u user global可能不可用。因此,您应该使用传递给此筛选器的$user global或$user参数。
示例更新代码:
function member_permalink( $user = null ) {
if ( null == $user || is_wp_error( $user ) ) {
$user_id = get_current_user_id();
} else {
$user_id = $user->ID;
}
$args = array(
\'post_type\' => \'cursist\',
\'author\' => $user_id,
\'numberposts\' => 1,
);
$current_user_posts = get_posts( $args );
if ( empty( $current_user_posts ) ) {
return;
}
$post_link = get_permalink( $current_user_posts[0] );
return $post_link;
}
function my_login_redirect( $redirect_to, $request, $user ) {
//is there a user to check?
if (isset($user->roles) && is_array($user->roles)) {
//check for subscribers
if (in_array(\'subscriber\', $user->roles)) {
// redirect them to another URL
$redirect_to = member_permalink( $user );
}
}
return $redirect_to;
}
add_filter( \'login_redirect\', \'my_login_redirect\', 10, 3 );
[编辑]:我做了
$user 参数可选,以提供灵活性,以防您在其他地方使用此函数时不带参数。