Home > Software engineering >  What does this error message mean: Uncaught Error: Call to a member function add_role() on bool
What does this error message mean: Uncaught Error: Call to a member function add_role() on bool

Time:10-31

I have this error message : Uncaught Error: Call to a member function add_role() on bool. I am trying to create a new user programmatically. This code works on another project I worked on, but returns an error on the current one am working on.

the code

$user_id = wp_create_user( $username, $password, $email );
        
        $user = get_user_by( 'id', $user_id );
        // Add role
        
        $user->add_role( 'customer' );
         

CodePudding user response:

It means that the $user does not return the user object, but false which means wp_create_user is probably returning an error object.

Check the wp_create_user arguments!

CodePudding user response:

Using the function wp_create_user will return either a user ID, or the WP_Error class https://developer.wordpress.org/reference/functions/wp_create_user/#return

With that being the case, you can check for error before you try to update the user and fetch the user id.

In your case, get_user_by is returning false, since there is no user returned from the first check. https://developer.wordpress.org/reference/functions/get_user_by/ we can avoid that all together by wrapping it in a check.

$user_id = wp_create_user( $username, $password, $email );
// check that wp_create_user was successful
if ( !is_wp_error( $user_id ) ) {
    $user = get_user_by( 'id', $user_id );
    // Add role
    $user->add_role( 'cust}omer' );
} 
  • Related