Sync all User Roles between two Wordpress Installs sharing the same wp_users and wp_usermeta tables.

后端 未结 1 871
忘掉有多难
忘掉有多难 2020-12-21 07:17

I have created a Woocommerce Store (database prefix wp_) and a Wordpress Blog (database prefix wp_new_) that share the same users (sharing the same wp_users and wp_user_meta

相关标签:
1条回答
  • 2020-12-21 07:43

    I had issues with syncing user roles (multiple user roles per user). After burning midnight oil for more than two nights I found the silly magical solution :)

    I simply changed 'set_user_role' to 'add_user_role' in "add_action( 'set_user_role', 'ksu_save_role', 10, 2 );"

    The end code after the small magical tweak

    function ksu_save_role( $user_id, $role ) {
    
        // Site 1
        // Change value if needed
        $prefix_1 = 'first_';
    
        // Site 2 prefix
        // Change value if needed
        $prefix_2 = 'second_';
    
        $caps = get_user_meta( $user_id, $prefix_1 . 'capabilities', true );
        $level = get_user_meta( $user_id, $prefix_1 . 'user_level', true );
    
        if ( $caps ){
            update_user_meta( $user_id, $prefix_2 . 'capabilities', $caps );
        }
    
        if ( $level ){
            update_user_meta( $user_id, $prefix_2 . 'user_level', $level );
        }
    }
    
    add_action( 'add_user_role', 'ksu_save_role', 10, 2 ); // THE MAGIC MODIFICATION
    

    Code credits: https://kinsta.com/blog/share-logins-wordpress/

    Add this to functions.php and you are great to go.

    It is compatible with role changer plugins like "Woocommerce Subscriptions" and "YITH Automatic Role Changer for WooCommerce Premium"

    You can set and change as many roles as you want.

    0 讨论(0)
提交回复
热议问题