Skip Navigation

[Resuelto] Help with cred api actions working together

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Our next available supporter will start replying to tickets in about 5.98 hours from now. Thank you for your understanding.

This topic contains 1 respuesta, has 2 mensajes.

Last updated by Waqar hace 2 años, 5 meses.

Assigned support staff: Waqar.

Autor
Mensajes
#1263183

Hi Support Team

I've added 2 functions to my child them that work on cred api hooks on a registration form

The first changes the username to a specific format and came after this thread:
https://toolset.com/forums/topic/auto-generate-username-from-form-fields/

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));
 
        }
    }
}

The second logs the user in automatically after registration and comes from this thread:
https://toolset.com/forums/topic/automatically-log-in-user-after-created/

/** Auto-login new CRED user */
add_action( 'cred_submit_complete', 'tw_cred_autologin', 10, 2 );
function tw_cred_autologin( $user_id, $form_data ){
 
	if ( $form_data['id'] == 48232 ) { // Edit as required
 		
		// get the user credentials from the $_POST object and the userdata
		$user_info = get_userdata($user_id);
		$cred = array(
			'user_login'    =>   $user_info->user_login,
//			'user_login'    =>   $_POST['user_login'],
			'user_password' =>   $_POST['user_pass'],
			'remember'      =>   true
        );
        $login = wp_signon( $cred, false );
 
        if ( is_wp_error($login) ) {
            error_log( $login->get_error_message() );
        }
		// 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']);
 
	}
}

My problem is that that when both actions are live, only the first one works. i.e. the username is changed but the user is not automatically logged in.

I've tested the second one and it works to log the user in if I comment out the first action.

I changed the login function to pull the username from $user_info->user_login instead of $_POST['user_login'] so I thought this would work to get the newly created username for login, instead of the original username.

Any ideas why they don't work together? Are the actions just happening so close together that the username hasn't been updated by the time the user login is grabbed, but then has been updated by the time it tries to log in?

Any guidance on this would be welcome.

#1263859

Waqar
Supporter

Languages: Inglés (English )

Timezone: Asia/Karachi (GMT+05:00)

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