Hi Tim,
Thank you for contacting us and I'd be happy to assist.
Your observation is correct and the function attached to the "cred_submit_complete" doesn't seem to log in the user since the new value of the "user_login" hasn't been updated by that time.
To overcome this and introduce some delay, you can follow these steps:
1. Please create a new "thank you" page for your regsiteration form and set it to show after a delay of 5-10 seconds.
( example screenshot: hidden link )
2. To get the values of the username and the password on the new thank you page, you can update your first code snippet to include these values in PHP's Session variable:
( ref: hidden link )
add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($user_id, $form_data)
{
// if a specific form
if ($form_data['id']==48232)
{
if(isset($_POST['first_name']) && isset($_POST['last_name'])){
$first_name = sanitize_title_with_dashes($_POST['first_name']);
$last_name = sanitize_title_with_dashes($_POST['last_name']);
$usercompany = sanitize_title_with_dashes(get_user_meta($user_id, 'wpcf-user-company', true));
$my_nickname = $usercompany . "-" . $first_name . "-" . $last_name;
$my_username = strtolower($my_nickname);
update_user_meta( $user_id, 'nickname', $my_nickname);
global $wpdb;
$wpdb->update($wpdb->users, array('user_login' => $my_username), array('ID' => $user_id));
// save the user login and password in a temp $_SESSION value
$_SESSION["userlogin"] = $my_username;
$_SESSION["userpass"] = $_POST['user_pass'];
}
}
}
3. You can replace the second code snippet with a new custom function attached to "wp" hook, which is set to only execute on the the form's thank you page and login the user, by getting the username and password values from the Session variable:
add_action("wp", "login_user_function");
function login_user_function(){
if(!is_admin()){
wp_reset_query();
// if this is a specific thank you page and the userlogin value is set in $_SESSION
if( (is_page(12345)) && (isset($_SESSION["userlogin"])) ){
$cred = array(
'user_login' => $_SESSION["userlogin"],
'user_password' => $_SESSION["userpass"],
'remember' => true
);
$login = wp_signon( $cred, false );
if ( is_wp_error($login) ) {
error_log( $login->get_error_message() );
}
else
{
// unset temp $_SESSION values
unset($_SESSION["userlogin"]);
unset($_SESSION["userpass"]);
}
// reloads the page to allow the login - not needed if cred form is set to go to a page or post.
wp_redirect($_SERVER['HTTP_REFERER']);
}
}
}
Note: Please replace "12345" with the actual ID of the form's thank you page.
I hope this helps and for more personalized assistance around custom code, you can also consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/
regards,
Waqar