TransWikia.com

WP_Error could not be converted to string

WordPress Development Asked by GamerBanaan on December 1, 2021

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:wamp64wwwwordpresswp-includesms-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);

2 Answers

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;
}

Answered by Mostafa Soufi on December 1, 2021

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.

Answered by Krzysiek Dróżdż on December 1, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP