我正在尝试为Wordpress Multisite安装构建以下功能:
我编写了以下代码,该代码在某种程度上有效。当用户登录时,他们当前被定向到他们的主博客,如果他们再次登录(即使他们已经登录),他们将被重定向到网关,这表明博客数量的计数在初始登录时不起作用。有没有人就我如何解决这个问题提出任何建议?
/*Redirect After Login on front end*/
function primary_login_redirect( $redirect_to, $request_redirect_to, $user )
{
if ($user->ID != 0)
{
$user_info = get_current_user_id();
//Get number of blogs from user
//$blogs = get_blogs_of_user( $user_info );
// if($blogs > 1) {
$user_blogs = get_blogs_of_user( $user_info );
$result = count($user_blogs);
if ($result > 1){
$primary_url = 'https://xxxyyyzzz.com/gateway-page/';
if ($primary_url) {
wp_redirect($primary_url);
die();
}
} else {
$user_info = get_userdata($user->ID);
if ($user_info->primary_blog) {
$primary_url = get_blogaddress_by_id($user_info->primary_blog) . 'home/';
if ($primary_url) {
wp_redirect($primary_url);
die();
}
}
}
return $redirect_to;
}
}
add_filter('login_redirect','primary_login_redirect', 100, 3);
答案 0 :(得分:1)
问题似乎是get_current_user_id()
在登录过程的这个阶段没有返回结果。
尝试从传递给方法的get_current_user_id()
参数中访问id,而不是使用$user
方法。
if ($user->ID != 0)
{
$userBlogs = get_blogs_of_user( $user->ID );
$numBlogs = count($userBlogs);
}
您可以重构代码,使其更具可读性。
function primary_login_redirect( $redirect_to, $request_redirect_to, $user )
{
if ($user->ID != 0)
{
$userBlogs = get_blogs_of_user($user->ID);
$numBlogs = count($userBlogs);
if ($numBlogs > 1) {
wp_redirect('https://xxxyyyzzz.com/gateway-page/');
die();
}
if ($user->primary_blog) {
$url = get_blogaddress_by_id($user->primary_blog) . 'home/';
wp_redirect($url);
die();
}
return $redirect_to;
}
}
答案 1 :(得分:0)
试试这个
<?php
function primary_login_redirect( $redirect_to, $request_redirect_to, $user )
{
if ($user->ID != 0)
{
$user_info = get_current_user_id();
//Get number of blogs from user
//$blogs = get_blogs_of_user( $user_info );
// if($blogs > 1) {
//$user_blogs = get_blogs_of_user( $user_info );
$result = count( get_posts( array( "post_type" => "post", "posts_per_page" => -1, "author" => $user_info )) );
if ($result > 1){
$primary_url = 'https://xxxyyyzzz.com/gateway-page/';
if ($primary_url) {
wp_redirect($primary_url);
die();
}
} else {
$user_info = get_userdata($user->ID);
if ($user_info->primary_blog) {
$primary_url = get_blogaddress_by_id($user_info->primary_blog) . 'home/';
if ($primary_url) {
wp_redirect($primary_url);
die();
}
}
}
return $redirect_to;
}
}
add_filter('login_redirect','primary_login_redirect', 100, 3);
?>
据我检查
echo json_encode(get_blogs_of_user( 1 )); // 1 is admin
它只返回
{"1":{"userblog_id":1,"blogname":"WOO","domain":"","path":"","site_id":1,"siteurl":"http:\/\/localhost\/wp","archived":0,"spam":0,"deleted":0}}
您的代码将始终提供1
。因此,计算自定义更好。