Created
August 15, 2017 04:52
-
-
Save codelion7/9121d09fa941072b666b535d4af2007c to your computer and use it in GitHub Desktop.
Sync the roles associated with each of the user's member types on each subsite of a multisite network
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Retrieves an array of all network sites | |
| * | |
| * @since 1.0 | |
| * @return array | |
| */ | |
| function get_network_sites() { | |
| global $wpdb; | |
| $blogs = $wpdb->get_results(" | |
| SELECT blog_id | |
| FROM {$wpdb->blogs} | |
| WHERE site_id = '{$wpdb->siteid}' | |
| AND spam = '0' | |
| AND deleted = '0' | |
| AND archived = '0' | |
| "); | |
| $sites = array(); | |
| $sites[0] = __( 'None', 'onesocial' ); | |
| foreach ( $blogs as $blog ) { | |
| $sites[ $blog->blog_id ] = get_blog_option( $blog->blog_id, 'blogname' ); | |
| } | |
| natsort( $sites ); | |
| unset( $sites[0] ); | |
| return apply_filters( 'network_sites', $sites ); | |
| } | |
| if ( class_exists( 'BuddyPress' ) ) { | |
| /** | |
| * Update role for all other subsites on member type change | |
| * | |
| * @param int $user_id numeric user id. | |
| * @param string $member_type new member type. | |
| * @param boolean $append whether the member type was appended or reset. | |
| */ | |
| function bp_ms_update_roles( $user_id, $member_type, $append ) { | |
| if ( ! function_exists( 'bpmtp_get_member_type_associated_roles' ) ) return; | |
| $sites = get_network_sites(); | |
| $original_site = get_current_blog_id(); | |
| foreach( $sites as $blog_id => $site_name ) { | |
| // Skip updating roles on the original site | |
| if ( $blog_id == $original_site ) | |
| continue; | |
| switch_to_blog( $blog_id ); | |
| $roles = bpmtp_get_member_type_associated_roles( $member_type ); | |
| // We do not modify roles if the user is super admin or the new roles list is empty. | |
| // Based on feedbak, we may want to remove all roles for empty in future. | |
| if ( empty( $roles ) || is_super_admin( $user_id ) ) { | |
| return; | |
| } | |
| $user = get_user_by( 'id', $user_id ); | |
| if ( ! $user ) { | |
| return; | |
| } | |
| // remove all roles. | |
| $user->set_role( '' ); | |
| // Now add the one/more roles to the user. | |
| foreach ( $roles as $role ) { | |
| $user->add_role( $role ); | |
| } | |
| restore_current_blog(); | |
| } | |
| } | |
| add_action( 'bp_set_member_type', 'bp_ms_update_roles', 10, 3 ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment