[WordPress] and issue with wp_insert_user() and wp_signon()

wizylabs said
<?php

// a short version of wp_insert_user(), no difference at all.
$new_user = wp_create_user( $username, $password, $email );

if( ! is_wp_error( $new_user ) )
{
	$creds = array();
	$creds['user_login'] = $username;
	$creds['user_password'] = $pass;
	$creds['remember'] = true;

	$signon = wp_signon( $creds, false );

	if ( is_wp_error( $signon ) )
	{
		// signed in, carry on
	}
	else
	{
		// echos out the errors, if any, from the login
		echo $signon->get_error_message();
	}
}
else
{
	// echos out the errors, if any, from the user insertion
	echo $new_user->get_error_message();
}

?>

above is a simplified code of my actual ones, not changed anything but stripped out the stuff that not necessary to debug :slight_smile:

the script inserts the user fine, but when it comes to login, it fails echoing out a message like “Username and password dont match” or something. The vars $username and $password and $email are defined earlier in the code.

maybe something like this?

function ft_insert_user(){
	$newUserData = array (
	   'ID' => '',
	   'user_pass' => wp_generate_password(),
	   'user_login' => 'ryan',
	   'user_nicename' => 'ryan',
	   'user_url' => '',
	   'user_email' => 'ryan at ryan.com',
	   'display_name' => 'Ryan',
	   'nickname' => 'ryan',
	   'first_name' => 'ryan',
	   'user_registered' => '2006-10-16 08:54:47',
	   'role' => 'Administrator'
	);
	
	$newUserId = wp_insert_user( $newUserData );
}
add_action( 'admin_init', 'ft_insert_user' );

and for automatic logging in.

<?php

function auto_login( $user ) {
    $username   = $user;
    // log in automatically
    if ( !is_user_logged_in() ) {
        $user = get_userdatabylogin( $username );
        $user_id = $user->ID;
        wp_set_current_user( $user_id, $user_login );
        wp_set_auth_cookie( $user_id );
        do_action( 'wp_login', $user_login );
    }     
}

?>

hopefully this helps.