Skip to content

Instantly share code, notes, and snippets.

@spacedmonkey
Created January 2, 2019 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spacedmonkey/817c7b7fcdc483913a39f02218a96f9d to your computer and use it in GitHub Desktop.
Save spacedmonkey/817c7b7fcdc483913a39f02218a96f9d to your computer and use it in GitHub Desktop.
function get_site_id_of_user( $user_id, $all = false ) {
global $wpdb;
$user_id = (int) $user_id;
// Logged out users can't have sites
if ( empty( $user_id ) ) {
return array();
}
$keys = get_user_meta( $user_id );
if ( empty( $keys ) ) {
return array();
}
$site_ids = array();
if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) {
$site_ids[1] = $keys[ $wpdb->base_prefix . 'capabilities' ];
unset( $keys[ $wpdb->base_prefix . 'capabilities' ] );
}
foreach ( $keys as $key => $value) {
if ( 'capabilities' !== substr( $key, -12 ) ) {
continue;
}
if ( $wpdb->base_prefix && 0 !== strpos( $key, $wpdb->base_prefix ) ) {
continue;
}
$site_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
if ( ! is_numeric( $site_id ) ) {
continue;
}
$site_ids[(int) $site_id] = $value;
}
return $site_ids;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment