0

I try to add an existing user to a blog with the function add_user_to_blog($blog_id, $user_id, $role). The code I use gives me:

Catchable fatal error: Object of class WP_Error could not be converted to string in C:\wamp64\www\wordpress\wp-includes\ms-functions.php on line 206.

What do I need to do to make this work?

This is my code:

$domain = "";
$path = "localhost/wordpress/wp_4";
$title = "WP_4";
$user_id = 1;
$network_id = get_main_network_id();
$role = 'editor';
$new_blog_id = wpmu_create_blog($domain, $path, $title, $user_id, $network_id);
add_user_to_blog($new_blog_id, $network_id, $role);
  • 3
    Please check your passed arguments. You're passing the network_id instead of the user_id as the second parameter. Also you should check the value of $new_blog_id to ensure you're getting an actual value there. – Fabian Marz Apr 3 '18 at 8:35
0

There are few problems with your code.

First of all, let's see at wpmu_create_blog function:

wpmu_create_blog(
    string $domain,
    string $path,
    string $title,
    int $user_id,
    array $meta = array(),
    int $network_id = 1
)

So you use it incorrectly. It's 5th argument is $meta and you put $network_id in there...

Another problem is that this function can return int (the ID of new site) or WP_Error if some error occured.

You ignore that and assume it always ends with success. And that is causing your error - function returns WP_Error and you treat it as int.

0

You should check your function result with is_wp_error()

<?php
$domain = "";
$path = "localhost/wordpress/wp_4";
$title = "WP_4";
$user_id = 1;
$network_id = get_main_network_id();
$role = 'editor';
$new_blog_id = wpmu_create_blog($domain, $path, $title, $user_id, $network_id);

if(is_wp_error($new_blog_id)) {
    echo $new_blog_id->get_error_message();
    return;
}

$new_user = add_user_to_blog($new_blog_id, $network_id, $role);

if(is_wp_error($new_user)) {
    echo $new_user->get_error_message();
    return;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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