get_active_blog_for_user

Get one of a user's active blogs.

Description

(WP_Site|void) get_active_blog_for_user( (int) $user_id ); 

Returns the user's primary blog, if they have one and it is active. If it's inactive, function returns another active blog of the user. If none are found, the user is added as a Subscriber to the Dashboard Blog and that blog is returned.

Returns (WP_Site|void)

The blog object

Parameters (1)

0. $user_id (int)
The unique ID of the user

Usage

  1. if ( !function_exists( 'get_active_blog_for_user' ) ) { 
  2. require_once ABSPATH . WPINC . '/ms-functions.php'; 
  3.  
  4. // The unique ID of the user 
  5. $user_id = -1; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = get_active_blog_for_user($user_id); 
  9.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/ms-functions.php  
  1. function get_active_blog_for_user( $user_id ) { 
  2. global $wpdb; 
  3. $blogs = get_blogs_of_user( $user_id ); 
  4. if ( empty( $blogs ) ) 
  5. return; 
  6.  
  7. if ( !is_multisite() ) 
  8. return $blogs[$wpdb->blogid]; 
  9.  
  10. $primary_blog = get_user_meta( $user_id, 'primary_blog', true ); 
  11. $first_blog = current($blogs); 
  12. if ( false !== $primary_blog ) { 
  13. if ( ! isset( $blogs[ $primary_blog ] ) ) { 
  14. update_user_meta( $user_id, 'primary_blog', $first_blog->userblog_id ); 
  15. $primary = get_site( $first_blog->userblog_id ); 
  16. } else { 
  17. $primary = get_site( $primary_blog ); 
  18. } else { 
  19. //TODO Review this call to add_user_to_blog too - to get here the user must have a role on this blog? 
  20. add_user_to_blog( $first_blog->userblog_id, $user_id, 'subscriber' ); 
  21. update_user_meta( $user_id, 'primary_blog', $first_blog->userblog_id ); 
  22. $primary = $first_blog; 
  23.  
  24. if ( ( ! is_object( $primary ) ) || ( $primary->archived == 1 || $primary->spam == 1 || $primary->deleted == 1 ) ) { 
  25. $blogs = get_blogs_of_user( $user_id, true ); // if a user's primary blog is shut down, check their other blogs. 
  26. $ret = false; 
  27. if ( is_array( $blogs ) && count( $blogs ) > 0 ) { 
  28. foreach ( (array) $blogs as $blog_id => $blog ) { 
  29. if ( $blog->site_id != $wpdb->siteid ) 
  30. continue; 
  31. $details = get_site( $blog_id ); 
  32. if ( is_object( $details ) && $details->archived == 0 && $details->spam == 0 && $details->deleted == 0 ) { 
  33. $ret = $blog; 
  34. if ( get_user_meta( $user_id , 'primary_blog', true ) != $blog_id ) 
  35. update_user_meta( $user_id, 'primary_blog', $blog_id ); 
  36. if ( !get_user_meta($user_id , 'source_domain', true) ) 
  37. update_user_meta( $user_id, 'source_domain', $blog->domain ); 
  38. break; 
  39. } else { 
  40. return; 
  41. return $ret; 
  42. } else { 
  43. return $primary;