The get_blogs_of_user WordPress PHP filter allows you to modify the list of sites a user belongs to.
Usage
add_filter('get_blogs_of_user', 'your_custom_function', 10, 3);
function your_custom_function($sites, $user_id, $all) {
// your custom code here
return $sites;
}
Parameters
$sites(object[]): An array of site objects belonging to the user.$user_id(int): User ID.$all(bool): Whether the returned sites array should contain all sites, including those marked ‘deleted’, ‘archived’, or ‘spam’. Default false.
More information
See WordPress Developer Resources: get_blogs_of_user
Examples
Exclude archived sites
Exclude archived sites from the list of sites a user belongs to.
add_filter('get_blogs_of_user', 'exclude_archived_sites', 10, 3);
function exclude_archived_sites($sites, $user_id, $all) {
foreach ($sites as $key => $site) {
if ($site->archived) {
unset($sites[$key]);
}
}
return $sites;
}
Add custom site to user’s list
Add a custom site to the list of sites a user belongs to.
add_filter('get_blogs_of_user', 'add_custom_site', 10, 3);
function add_custom_site($sites, $user_id, $all) {
$custom_site = new stdClass();
$custom_site->blog_id = 999;
$custom_site->userblog_id = 999;
$sites[] = $custom_site;
return $sites;
}
Limit the number of sites returned
Limit the number of sites returned to a maximum of 5.
add_filter('get_blogs_of_user', 'limit_sites_returned', 10, 3);
function limit_sites_returned($sites, $user_id, $all) {
return array_slice($sites, 0, 5);
}
Sort sites by blog ID
Sort the sites a user belongs to by their blog ID.
add_filter('get_blogs_of_user', 'sort_sites_by_blog_id', 10, 3);
function sort_sites_by_blog_id($sites, $user_id, $all) {
usort($sites, function($a, $b) {
return $a->blog_id <=> $b->blog_id;
});
return $sites;
}
Filter sites by user role
Return only the sites where the user has an ‘editor’ role.
add_filter('get_blogs_of_user', 'filter_sites_by_editor_role', 10, 3);
function filter_sites_by_editor_role($sites, $user_id, $all) {
$filtered_sites = [];
foreach ($sites as $site) {
switch_to_blog($site->userblog_id);
$user = get_user_by('id', $user_id);
if (in_array('editor', $user->roles)) {
$filtered_sites[] = $site;
}
restore_current_blog();
}
return $filtered_sites;
}