Using WordPress ‘pre_get_blogs_of_user’ PHP filter

The pre_get_blogs_of_user filter allows you to modify the list of a user’s sites before it is populated.

Returning a non-null value will short circuit the get_blogs_of_user() function, returning the modified value instead.

Usage

add_filter('pre_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 null|object[]: An array of site objects that the user is a member of.
  • $user_id int: The User ID.
  • $all bool: Whether the returned array should contain all sites, including those marked ‘deleted’, ‘archived’, or ‘spam’. Default is false.

More Information

See WordPress Developer Resources: pre_get_blogs_of_user

Examples

Exclude archived sites

Exclude archived sites from the list of user’s sites.

add_filter('pre_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;
}

Include only sites with a specific theme

Include only sites that use a specific theme.

add_filter('pre_get_blogs_of_user', 'filter_sites_by_theme', 10, 3);

function filter_sites_by_theme($sites, $user_id, $all) {
  $filtered_sites = array();
  $theme = 'my-theme';

  foreach ($sites as $site) {
    switch_to_blog($site->userblog_id);
    if (get_template() == $theme) {
      $filtered_sites[] = $site;
    }
    restore_current_blog();
  }
  return $filtered_sites;
}

Sort sites by blog name

Sort the user’s sites by blog name.

add_filter('pre_get_blogs_of_user', 'sort_sites_by_blog_name', 10, 3);

function sort_sites_by_blog_name($sites, $user_id, $all) {
  usort($sites, function($a, $b) {
    return strcmp($a->blogname, $b->blogname);
  });
  return $sites;
}

Limit the number of sites returned

Limit the number of sites returned for the user.

add_filter('pre_get_blogs_of_user', 'limit_user_sites', 10, 3);

function limit_user_sites($sites, $user_id, $all) {
  $max_sites = 5;
  return array_slice($sites, 0, $max_sites);
}

Remove sites marked as spam

Remove sites marked as spam from the list of user’s sites.

add_filter('pre_get_blogs_of_user', 'remove_spam_sites', 10, 3);
function remove_spam_sites($sites, $user_id, $all) {
    foreach ($sites as $key => $site) {
        if ($site->spam) {
            unset($sites[$key]);
        }
    }
    return $sites;
}