0

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 (); ?
1
  • Can you copy actual code into your question? Add_action should give a PHP fatal error for the upper case A, and there are spaces in strange places. add_action also expects a callable type value as the second parameter, e.g. a function name
    – Tom J Nowell
    Commented May 19, 2017 at 12:46

1 Answer 1

0

You said you wanna register any user to other blogs when a user is created. But this get_current_user_id() doesn't fire on user creation. You better have a look on wp-includes/user.php at line 1401 the wp_insert_user function. WordPress default registering process uses this function to insert new users. And if you wanna create the user manually then you're also using this function. So if you use this user_register hook declared at line 1707 at wp-includes/user.php inside wp_insert_user function then we can say that the hook will be executed all the time of creating new user and when the user is being created we'll assign this user to other blog like this-

$blog_id = 1;
//$user_id = 127; // You don't need to define user_id here.
$role = 'publisher';

add_action( 'user_register', function( $user_id ) use ( $blog_id, $role ) {
    add_user_to_blog ($blog_id, $user_id, $role);
}, 10, 1 );

Now come the problem of your code-

  1. You can't do it like Add_action ('user_register', add_user_to_blog ($ blog_id, $ user_id, $ role));. The first mistake is it's add_action, small case a.
  2. Second mistake is the second parameter doesn't take add_user_to_blog ($ blog_id, $ user_id, $ role) this kinda value. It takes a string which represents a callable function name.
  3. You've defined the variable with capital letter and called with small letter.
  4. You passed the variable to the callable function wrong way. Se my answer code for the fix.

Note that I used anonymous function and also used use keyword to pass value from outside.

Hope that helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.