Adding users to another blog (Wordpress Multisite)

Good Morning...

I want to make a snippet that when creating a user in a blog add it automatically to another blog (this number 1 always) with the same roll that was created.

For this I am using this:

$ Blog_id = 1;
$ User_id = get_current_user_id ();
$ Role = 'publisher';
Add_action ('user_register', add_user_to_blog ($ blog_id, $ user_id, $ role));

.....And it does not work,

but if I do this....

$ Blog_id = 1;
$ User_id = 127; // 127 is a specific number of a user that already exists
$ Role = 'publisher';
Add_action ('user_register', add_user_to_blog ($ blog_id, $ user_id, $ role));

Then yes that works.

Can someone help me understand why the first (generic) solution does not work with:

$ User_id = get_current_user_id (); ?

Solution 1:

get_current_user_id function returns the current logged in user. It's not new user ID.

Get the current user’s ID

You should use something like this:

add_action( 'user_register', 'myplugin_registration_save', 10, 1 );

function myplugin_registration_save( $user_id ) {
    $blog_id = 1;
    add_user_to_blog($blog_id, $user_id, "publisher");

}

I didn't test it but it should work fine.