0

I am working on a custom sign up proces where a user first fills in his name and email, then receives an activation e-mail and then the sign up proces continues.

The e-mail contains an activation link with a reference. I need to save this reference in my new user so if the user clicks on the link I can retrieve back the user data.

But for some reason I cannot add my user meta data by inserting the new user.

So first I have my form handling where I get the POST values. And If they are true I start this code:

$ref = md5( get_bloginfo( 'name' ) . $reg_email );
$activation_url = get_bloginfo( 'wpurl' ) . '/search-company?ref=' . $ref;

// Create user
$random_password = wp_generate_password( 12, true, false );
$user_id = username_exists( $email );
$userdata = array(
  'user_login'  => $email,
  'user_pass'   => $random_password,
  'user_email'  => $email,
  'first_name'  => $first_name,
  'last_name'   => $surname,
  'role'            => 'author',
);
wp_insert_user( $userdata );
add_user_meta( $userdata, 'verification_ref', $ref );

And then I send my e-mail by wp_mail() with the activation link, this works fine, but I only need to save the verification reference in the user meta of the user.

2 Answers 2

5

wp_insert_user returns your new user's ID, if created successful. You can add the user_meta to this ID:

$userid = wp_insert_user( $userdata );
if ( !is_wp_error( $userid ) ) { // check if insert was successful
    add_user_meta( $userid, 'verification_ref', $ref ); // add the meta
} else {
    /* Error Handling */
}
0
1

I wrote this code for you, which can register the user in the first step and then enter the registered user to the management dashboard.

You can also use this code to save any user meta you want in the database.

I hope this code is useful for friends.

/**
* User registration
*/

function prefix_register_user()
{
    $userdata  = array(
        'user_login'  => $email,
        'user_pass'   => $random_password,
        'user_email'  => $email,
        'first_name'  => $first_name,
        'last_name'   => $surname,
        'role'            => 'author',
    );
    $userid = wp_insert_user( $userdata );
    if ( !is_wp_error( $userid ) ) { // check if insert was successful
        update_user_meta( $userid, 'billing_phone', '+98' ); // add woocommerce account phone number
        $user_data = get_user_by("id", $userid);
        prefix_login_user($user_data);
        wp_redirect(get_permalink(get_option('woocommerce_myaccount_page_id')));
    }

}

/**
* loggedin the registered user to the dashboard
*/

function prefix_login_user($user)
{
    wp_set_current_user($user->ID, $user->user_login);
    wp_set_auth_cookie($user->ID);
    do_action('wp_login', $user->user_login, $user);
}

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.