简体   繁体   中英

WordPress add user role with $ultimatemember

I'm creating a wordpress user like this :

$userdata = array(
        'user_login' =>  $login,
        'user_pass'  =>  $pass,
        'user_email' => $mail,
    );
    $user_id = wp_insert_user($userdata);

and I want to add a user role using Ultimate Member like this :

 global $ultimatemember;
    um_fetch_user($user_id);
    $ultimatemember->user->set_role('role-slug');

But when I do it like this, I have an error

Uncaught Error: Call to a member function set_role() on null

I've tried before with a row 'role' => 'role_slug' in the userdata but it doesn't work :(

Hope this help you

$userdata = array(
        'user_login' =>  $login,
        'user_pass'  =>  $pass,
        'user_email' => $mail,
    );
$user_id = wp_insert_user($userdata);


$wp_user_object = new WP_User($user_id );
$wp_user_object->set_role('editor');

What you're doing is basically like this:
https://docs.ultimatemember.com/article/32-change-user-community-role

Which is correct, if you have installed the ultimatemember plugin


It might be failing because the provided $user_id is not a valid user-id.

wp_insert_user will return either int (id for the user) or WP_Error : https://developer.wordpress.org/reference/functions/wp_insert_user/

Read up on WP_Error : https://developer.wordpress.org/reference/classes/wp_error/


If wp_insert_user returns an error, there could be many causes:

  • Passing invalid email address.
  • Email address is allready taken by a different user.
  • Other plugins have added restrictions on password strength, or any other requirement .

With filter_var we can check if the email is valid:
https://www.php.net/manual/en/function.filter-var.php

And with is_wp_error we can check if wp_insert_user returns a WP_Error :
https://developer.wordpress.org/reference/functions/is_wp_error/

With these functions, we can find and avoid the issue:

// check if email is valid
if( false === filter_var($mail, FILTER_VALIDATE_EMAIL) ){
    echo 'The email is invalid';
    return;
}


$userdata = [
    'user_login' =>  $login,
    'user_pass'  =>  $pass,
    'user_email' =>  $mail,
];

$user_id = wp_insert_user($userdata);

// check if error occurred
if( is_wp_error($user_id) ){
    echo $user_id->get_error_message(); // <-- this should reveal the cause of the issue
    return; 
}



global $ultimatemember;
um_fetch_user($user_id);

$ultimatemember->user->set_role('role-slug');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM