获取用户的一个活跃博客

原型

get_active_blog_for_user( int $user_id )

描述

返回用户的主要博客,如果他们有一个并且它是活动的。如果它处于非活动状态,则函数将返回该用户的另一个活动博客。如果未找到,则将用户添加为Dashboard Blog的订阅者,并返回该博客。

参数

$user_id (int) (Required) 用户的唯一ID

返回值

(WP_Site|void)  博客对象

源文件

路径:wp-includes/ms-functions.php

<?php
...
function get_active_blog_for_user( $user_id ) {
	$blogs = get_blogs_of_user( $user_id );
	if ( empty( $blogs ) )
		return;
	if ( ! is_multisite() ) {
		return $blogs[ get_current_blog_id() ];
	}
	$primary_blog = get_user_meta( $user_id, 'primary_blog', true );
	$first_blog = current($blogs);
	if ( false !== $primary_blog ) {
		if ( ! isset( $blogs[ $primary_blog ] ) ) {
			update_user_meta( $user_id, 'primary_blog', $first_blog->userblog_id );
			$primary = get_site( $first_blog->userblog_id );
		} else {
			$primary = get_site( $primary_blog );
		}
	} else {
		//TODO Review this call to add_user_to_blog too - to get here the user must have a role on this blog?
		$result = add_user_to_blog( $first_blog->userblog_id, $user_id, 'subscriber' );
		if ( ! is_wp_error( $result ) ) {
			update_user_meta( $user_id, 'primary_blog', $first_blog->userblog_id );
			$primary = $first_blog;
		}
	}
	if ( ( ! is_object( $primary ) ) || ( $primary->archived == 1 || $primary->spam == 1 || $primary->deleted == 1 ) ) {
		$blogs = get_blogs_of_user( $user_id, true ); // if a user's primary blog is shut down, check their other blogs.
		$ret = false;
		if ( is_array( $blogs ) && count( $blogs ) > 0 ) {
			foreach ( (array) $blogs as $blog_id => $blog ) {
				if ( $blog->site_id != get_current_network_id() )
					continue;
				$details = get_site( $blog_id );
				if ( is_object( $details ) && $details->archived == 0 && $details->spam == 0 && $details->deleted == 0 ) {
					$ret = $blog;
					if ( get_user_meta( $user_id , 'primary_blog', true ) != $blog_id )
						update_user_meta( $user_id, 'primary_blog', $blog_id );
					if ( !get_user_meta($user_id , 'source_domain', true) )
						update_user_meta( $user_id, 'source_domain', $blog->domain );
					break;
				}
			}
		} else {
			return;
		}
		return $ret;
	} else {
		return $primary;
	}
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/get_active_blog_for_user/