Home » Sync Roles of Multisite Users

Sync Roles of Multisite Users

So this happened at work today, was working on a multiste and the client required that under a certain condition. For now lets say the condition is that I’m subscribing to the site and for 5 days i’m a free user on the 5th day i need the client to revert to role => unpaid.

In my functions.php file i have this code

function mysite_sync_site_roles($user_id = NULL)
{
// is_multisite() used just as precaution, this code is meant to Multisite only
    if( !is_multisite())
        return;
    // Initial data
	$user_info = get_userdata( $user_id ); 
	if(in_array('administrator', $user_info->roles))
		return;
    $blogs = get_blogs_of_user( $user_id );
    $original_blog_id = get_current_blog_id();
    // Iterate through blogs of user
    foreach ( $blogs as $blog ){
        // Work with another site
        switch_to_blog( $blog->userblog_id );
        // Grab all user info and update role as in main site
           $id = wp_update_user( array ( 'ID' => $user_id, 'role' => 'unpaid' ) ) ;
           $var .= $blog->userblog_id."::".$id;
           restore_current_blog();
 	 }
 	 		$var .="if nothing before this error";
 	
    // Back to original main site
   			 switch_to_blog( $original_blog_id );  
    		// make sure current site role is changed
    		$id = wp_update_user( array ( 'ID' => $user_id, 'role' => 'unpaid' ) ) ;
    		$var .= "\n for current site".$id;
     		$handle = fopen("sync.txt", "w+");
             fwrite($handle,$var);
             fclose($handle);

}

Note: first of all you’ll need a role called unpaid to be registered across the multisite.

function social_roles(){
	add_role( 'unpaid', __( 'Unpaid','twentythirteen' ), array(
	                'read'                      => false,
	                'edit_posts'                => false,
	                'delete_posts'              => false
	) );

	add_role( 'trial', __( 'Trial','twentythirteen' ), array(
	                'read'                      => false,
	                'edit_posts'                => false,
	                'delete_posts'              => false
	) );
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Filter