Last active
August 29, 2015 14:07
-
-
Save micc83/db2c2875773b17d6823e to your computer and use it in GitHub Desktop.
Sync roles between different WordPress Blog inside the same schema on first login
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
<?php | |
/** | |
* Sync roles between different WordPress Blog | |
* | |
* Tables must be inside the same schema and you have to define | |
* custom user tables on wp-config.php in the SLAVE blog as follow: | |
+ define('CUSTOM_USER_TABLE', 'myprefix_users'); | |
+ define('CUSTOM_USER_META_TABLE', 'myprefix_usermeta'); | |
* Sync is run only at the first login on the alternative blog, any following | |
* role change must be manually sync. | |
* If blogs shares the same main domain (ex. domain.it - blog.domain.it) you can | |
* share logon cookies adding the following to wp-config.php: | |
+ $root_host = 'epilbeauty.it'; | |
+ define( 'COOKIE_DOMAIN', '.'.$root_host ); | |
+ define( 'COOKIEHASH', md5('http://'.$root_host) ); | |
* | |
* @param String $alt_table_prefix Alternative blog table prefix (ex. 'myprefix_') | |
*/ | |
function wp_sync_roles_with( $alt_table_prefix ) { | |
global $wpdb; | |
// Get current user id | |
$uid = get_current_user_id(); | |
// if user not logged or role already been set (save a query) exit | |
if (!$uid || current_user_can('read')) return; | |
// Get role on current blog | |
$role = $wpdb->get_var("SELECT meta_value FROM {$wpdb->usermeta} WHERE meta_key = '".$wpdb->get_blog_prefix()."capabilities' AND user_id = {$uid}"); | |
// If a role is already set (non default capabilities) exit | |
if ($role) return; | |
// Get the role in the alternative blog | |
$newrole = $wpdb->get_var("SELECT meta_value FROM {$wpdb->usermeta} WHERE meta_key = '{$alt_table_prefix}capabilities' AND user_id = {$uid}"); | |
$rarr = unserialize($newrole); | |
$roles = is_array($rarr) ? array_keys($rarr) : array('non-user'); | |
$newrole = $roles[0]; | |
// Set new role on current blog | |
$wp_user_object = new WP_User($uid); | |
$wp_user_object->add_role( $newrole ); | |
// Page must be reloaded now | |
wp_safe_redirect($_SERVER['REQUEST_URI']); | |
exit; | |
} | |
wp_sync_roles_with('f7sr6w_'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment