Accueil › Toolset Professional Support › [Résolu] Automatic Login with Autogenerated login.
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.
Aucun de nos assistants n'est disponible aujourd'hui sur le forum Jeu d'outils. Veuillez créer un ticket, et nous nous le traiterons dès notre prochaine connexion. Merci de votre compréhension.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
- | 10:00 – 13:00 | 10:00 – 13:00 | 10:00 – 13:00 | 10:00 – 13:00 | 10:00 – 13:00 | - |
- | 14:00 – 18:00 | 14:00 – 18:00 | 14:00 – 18:00 | 14:00 – 18:00 | 14:00 – 18:00 | - |
Supporter timezone: Asia/Kolkata (GMT+05:30)
Ce sujet contient 18 réponses, a 2 voix.
Dernière mise à jour par Minesh Il y a 2 années et 9 mois.
Assisté par: Minesh.
Tell us what you are trying to do?
I have created a registration form with Toolset Forms. I have some functions to automaticall create a username and to allow registration without an email. I am trying to combine this with automatic login. I think I am 99.9% there, but am struggling to work out how to pass the generated username into the auto login function.
Is there any documentation that you are following?
https://wordpress.stackexchange.com/questions/296101/auto-assign-sequence-base-username-while-registration
https://toolset.com/forums/topic/automatically-log-in-user-after-created/
Please see my code below:
/* @since 2.1.0 * * @param WP_Error $errors A WP_Error object containing any errors encountered * during registration. * @param string $sanitized_user_login User's username after it has been sanitized. * @param string $user_email User's email. */ add_filter( 'registration_errors', 'smyles_allow_wp_login_register_empty_user_login', 9999, 3 ); /** * Allow empty user_login (username) from wp-login.php registration form * * * @since @@version * * @param $errors WP_Error * @param $sanitized_user_login * @param $user_email * * @return mixed */ function smyles_allow_wp_login_register_empty_user_login( $errors, $sanitized_user_login, $user_email ){ // First remove empty_username error code to make sure there aren't any other errors $errors->remove( 'empty_username' ); $error_codes = $errors->get_error_codes(); // Return errors and don't process further (we only want to proceed when empty_username is only error code) if( ! empty( $error_codes ) ){ return $errors; } return $errors; } /** This is done by filtering on the registration errors for wp-login.php and removing the empty_username one. Next you will need a helper function to generate the sequential username, with the padded zeros. This function uses a length of 10 characters, increasing it by one for each new user. This also verifies the user_login does not exist before setting it to that value. */ /** * Generate sequential padded user_login * * @author Myles McNamara * * @return string */ function smyles_generate_next_seq_user_login(){ // Use 0 as default (if option does not exist yet), as 1 will be used for first user $last_user_num = get_option( 'smyles_custom_seq_usernames_last_id', 0 ); // Create padded username total length of 10 characters, increasing last ID by 1 $gen_user_login = str_pad( (int) $last_user_num + 1, 10, 0, STR_PAD_LEFT ); if( username_exists( $gen_user_login ) ){ // If generated new user login exists, update our last id +1 and do recursive call update_option( 'smyles_custom_seq_usernames_last_id', (int) $last_user_num + 1 ); return smyles_generate_next_seq_user_login(); } return $gen_user_login; } add_filter( 'pre_user_login', 'smyles_custom_username_seq_pre_user_login' ); /** * Set user_login to generated value, only if passed value is empty * * @author Myles McNamara * * @param $sanitized_user_login * * @return string */ function smyles_custom_username_seq_pre_user_login( $sanitized_user_login ){ $sanitized_user_login = trim( $sanitized_user_login ); // to match wp_insert_user handling /** * The user_login should be empty string when creating from wp-login.php registration page, * otherwise will contain a value when called by something else. * * There is a chance this will be called for updating a user (which is incorrect as wp_update_user should be called), * but even when updating a user, the passed user_login should have some type of value. */ if( empty( $sanitized_user_login ) || $sanitized_user_login === 'GENERATE_CUSTOM_SEQ_USERNAME' ){ $sanitized_user_login = smyles_generate_next_seq_user_login(); } return $sanitized_user_login; } /** * Filters a user's meta values and keys immediately after the user is created or updated * and before any user meta is inserted or updated. * * Does not include contact methods. These are added using `wp_get_user_contact_methods( $user )`. * * @since 4.4.0 * * @param array $meta { * Default meta values and keys for the user. * * @type string $nickname The user's nickname. Default is the user's username. * @type string $first_name The user's first name. * @type string $last_name The user's last name. * @type string $description The user's description. * @type bool $rich_editing Whether to enable the rich-editor for the user. False if not empty. * @type bool $syntax_highlighting Whether to enable the rich code editor for the user. False if not empty. * @type bool $comment_shortcuts Whether to enable keyboard shortcuts for the user. Default false. * @type string $admin_color The color scheme for a user's admin screen. Default 'fresh'. * @type int|bool $use_ssl Whether to force SSL on the user's admin area. 0|false if SSL is * not forced. * @type bool $show_admin_bar_front Whether to show the admin bar on the front end for the user. * Default true. * } * * @param WP_User $user User object. * @param bool $update Whether the user is being updated rather than created. */ add_filter( 'insert_user_meta', 'smyles_custom_username_seq_verify', 10, 3 ); /** * Verify user was created, and then increase option value * * * @author Myles McNamara * * @param $meta * @param $user WP_User * @param $update * * @return mixed */ function smyles_custom_username_seq_verify( $meta, $user, $update ){ // Don't want to verify if this is just an update call if( ! $update && $user && $user->user_login ){ // Check what the last user num was stored as $last_user_num = get_option( 'smyles_custom_seq_usernames_last_id', 0 ); // Verify that user_login of the user that was created, matches what is supposed to be the next user_login if( (int) $last_user_num + 1 === (int) $user->user_login ){ // Update our option after verification update_option( 'smyles_custom_seq_usernames_last_id', (int) $user->user_login ); // Type casting to int causes 0000000001 to be 1 (trim leading zeros) } } return $meta; } /** * Auto log-in new user */ add_action( 'cred_save_data', 'tssupp_cred_autologin', 10, 2 ); function tssupp_cred_autologin( $post_id, $form_data, $gen_user_login ){ if ( 1194 == $form_data['id'] ) { if ( !empty( $gen_user_login ) && !empty( $_POST['user_pass'] ) ) { $user = get_user_by( "login", $gen_user_login ); $signon = array( 'user_login' => $user->user_login, 'user_password' => $_POST['user_pass'], 'remember' => true ); $login = wp_signon( $signon, false ); if ( is_wp_error($login) ) { error_log( $login->get_error_message() ); } } } }
Hello. Thank you for contacting the Toolset support.
I'm not exactly sure where exactly you want help with. Do you need help with the login code you added with cred_save_data hook or with other custom code?
Yes. I need help with the autologin function using cred_save_data.
I need to understand how to pass the username (created above) into this function, in order to get the user and credentials to complete the login.
You do not have to pass it.
The "cred_save_data" hook allows doing a custom action when post data is saved to database. That mean this will run after user is saved to database.
=> https://toolset.com/documentation/programmer-reference/cred-api/#cred_save_data
You can login using the username and password saved to database.
What if you try to use the following code:
add_action( 'cred_save_data', 'tssupp_cred_autologin', 10, 2 ); function tssupp_cred_autologin( $post_id, $form_data ){ if ( 1194 == $form_data['id'] ) { if ( !empty( $_POST['user_pass'] ) ) { $user = get_user_by( "login", $post_id ); $signon = array( 'user_login' => $user->user_login, 'user_password' => $_POST['user_pass'], 'remember' => true ); $login = wp_signon( $signon, false ); if ( is_wp_error($login) ) { error_log( $login->get_error_message() ); } } } }
Does that helps?
I get the following error upon submission of the form:
Fatal error: Uncaught ArgumentCountError: Too few arguments to function tssupp_cred_autologin(), 1 passed in /home/customer/www/staging.apetece.com.br/public_html/wp-content/themes/apetece-herois/functions.php on line 142 and exactly 2 expected in /home/customer/www/staging.apetece.com.br/public_html/wp-content/themes/apetece-herois/functions.php:208 Stack trace: #0 /home/customer/www/staging.apetece.com.br/public_html/wp-content/themes/apetece-herois/functions.php(142): tssupp_cred_autologin('0000000048') #1 /home/customer/www/staging.apetece.com.br/public_html/wp-includes/class-wp-hook.php(307): smyles_custom_username_seq_pre_user_login('0000000048') #2 /home/customer/www/staging.apetece.com.br/public_html/wp-includes/plugin.php(189): WP_Hook->apply_filters('GENERATE_CUSTOM...', Array) #3 /home/customer/www/staging.apetece.com.br/public_html/wp-includes/user.php(1945): apply_filters('pre_user_login', 'GENERATE_CUSTOM...') #4 /home/customer/www/staging.apetece.com.br/public_html/wp-content/plugins/cred-frontend-editor/li in /home/customer/www/staging.apetece.com.br/public_html/wp-content/themes/apetece-herois/functions.php on line 208
Are you sure this is right?
$user = get_user_by( "login", $post_id );
What if you try the following code as based on your custom code it seems you are trying to generate the username.
So, as "cred_save_data" we have will be fired after user is created and we will have user ID access, so we will try to get the user object based on user ID.
If following code not work then I will require to check whats going wrong with your setup.
add_action( 'cred_save_data', 'tss. upp_cred_autologin', 10, 2 ); function tssupp_cred_autologin( $post_id, $form_data ){ if ( 1194 == $form_data['id'] ) { $user = get_user_by( "id", $post_id ); $signon = array( 'user_login' => $user->user_login, 'user_password' => $_POST['user_pass'], 'remember' => true ); $login = wp_signon( $signon, false ); if ( is_wp_error($login) ) { error_log( $login->get_error_message() ); } } }
If above code does not work, please share problem URL and steps I will have to follow with admin access details.
*** Please make a FULL BACKUP of your database and website.***
I would also eventually need to request temporary access (WP-Admin and FTP) to your site. Preferably to a test site where the problem has been replicated if possible in order to be of better help and check if some configurations might need to be changed.
I have set the next reply to private which means only you and I have access to it.
But where you added the Toolset User form using which we can register the user? To what page/post?
Can you please share steps I've to follow to register the user?
Apologies. Of course.
The login form is located here: lien caché
The desired outcome is that the user completes the form and submits. The user is then created, the user logged in, and then the page reloaded.
Can you please share where you added the custom code you shared with your initial reply?
There is no custom shortcode. Just a Toolset Forms User Form, included on the page via the Blocks interface.
You will need to be in a logged out state to see the form as it is within a conditional, so better to test preview in incognito.
Note:
What the above code does is remove required validation for the username field. It then checks, when creating user, if the username field is populated or empty. If empty it creates a username in a sequencial number format.
Sorry. I misread. The code is in functions.php
You will see, now, that there are two forms. "Sign-up with email" and "sign-up without email"
I have autologin working on the "sign-up with email" form, as we retreive the user by the email address.
On the other form, the one we are dealing with, "sign-up without email", I need to use the generated username as the lookup for the user, to complete the array for login. I'm just not sure how to call it into the tssupp_cred_autologin action.
It's working a lot smother, now, and creates the user without producing any PHP errors. I believe I also now have the generated username variable loaded in the tssupp_cred_autologin.
However, it's still not completing the login. It feels like the tiniest thing would make it work at this point.
I see functions.php file having two cred_save_data hook, one for form ID 3137 and another for form ID 1194 where one form having email and another is not.
After many attempts finally, I'm able to share the solution. Following is the updated code added the functions.php file:
add_action( 'cred_save_data', 'tssupp_cred_autologin', 999, 2 ); function tssupp_cred_autologin( $new_user_id, $form_data ){ // Login without email if ( 1194 == $form_data['id'] ) { remove_filter('pre_user_login','smyles_custom_username_seq_pre_user_login'); $my_username = smyles_generate_next_seq_user_login(); if ( !empty( $_POST['user_pass'] ) ) { $newuser = get_user_by( "id", $new_user_id ); $signon = array( 'user_login' => $newuser->data->user_login, 'user_password' => $_POST['user_pass'], 'remember' => true ); $login = wp_signon( $signon, false ); if ( is_wp_error($login) ) { error_log( $login->get_error_message() ); } } }; // Login with email if ( 3137 == $form_data['id'] ) { if ( !empty( $_POST['user_email'] ) && !empty( $_POST['user_pass'] ) ) { $user = get_user_by( "email", $_POST['user_email'] ); $signon = array( 'user_login' => $user->user_login, 'user_password' => $_POST['user_pass'], 'remember' => true ); $login = wp_signon( $signon, false ); if ( is_wp_error($login) ) { error_log( $login->get_error_message() ); } } }; }
Can you please try to register using without email form and check if it works as expected.
Please note the "$my_usernme" variable... it's just not completing the login for form ID 1194
/* @since 2.1.0 * * @param WP_Error $errors A WP_Error object containing any errors encountered * during registration. * @param string $sanitized_user_login User's username after it has been sanitized. * @param string $user_email User's email. */ add_filter( 'registration_errors', 'smyles_allow_wp_login_register_empty_user_login', 9999, 3 ); /** * Allow empty user_login (username) from wp-login.php registration form * * * @since @@version * * @param $errors WP_Error * @param $sanitized_user_login * @param $user_email * * @return mixed */ function smyles_allow_wp_login_register_empty_user_login( $errors, $sanitized_user_login, $user_email ){ // First remove empty_username error code to make sure there aren't any other errors $errors->remove( 'empty_username' ); $error_codes = $errors->get_error_codes(); // Return errors and don't process further (we only want to proceed when empty_username is only error code) if( ! empty( $error_codes ) ){ return $errors; } return $errors; } /** This is done by filtering on the registration errors for wp-login.php and removing the empty_username one. Next you will need a helper function to generate the sequential username, with the padded zeros. This function uses a length of 10 characters, increasing it by one for each new user. This also verifies the user_login does not exist before setting it to that value. */ /** * Generate sequential padded user_login * * @author Myles McNamara * * @return string */ function smyles_generate_next_seq_user_login(){ // Use 0 as default (if option does not exist yet), as 1 will be used for first user $last_user_num = get_option( 'smyles_custom_seq_usernames_last_id', 0 ); // Create padded username total length of 10 characters, increasing last ID by 1 $gen_user_login = str_pad( (int) $last_user_num + 1, 10, 0, STR_PAD_LEFT ); if( username_exists( $gen_user_login ) ){ // If generated new user login exists, update our last id +1 and do recursive call update_option( 'smyles_custom_seq_usernames_last_id', (int) $last_user_num + 1 ); return smyles_generate_next_seq_user_login(); } return $gen_user_login; } add_filter( 'pre_user_login', 'smyles_custom_username_seq_pre_user_login' ); /** * Set user_login to generated value, only if passed value is empty * * @author Myles McNamara * * @param $sanitized_user_login * * @return string */ function smyles_custom_username_seq_pre_user_login( $sanitized_user_login ){ $sanitized_user_login = trim( $sanitized_user_login ); // to match wp_insert_user handling /** * The user_login should be empty string when creating from wp-login.php registration page, * otherwise will contain a value when called by something else. * * There is a chance this will be called for updating a user (which is incorrect as wp_update_user should be called), * but even when updating a user, the passed user_login should have some type of value. */ if( empty( $sanitized_user_login ) || $sanitized_user_login === 'GENERATE_CUSTOM_SEQ_USERNAME' ){ $sanitized_user_login = smyles_generate_next_seq_user_login(); } return $sanitized_user_login; } /** * Filters a user's meta values and keys immediately after the user is created or updated * and before any user meta is inserted or updated. * * Does not include contact methods. These are added using `wp_get_user_contact_methods( $user )`. * * @since 4.4.0 * * @param array $meta { * Default meta values and keys for the user. * * @type string $nickname The user's nickname. Default is the user's username. * @type string $first_name The user's first name. * @type string $last_name The user's last name. * @type string $description The user's description. * @type bool $rich_editing Whether to enable the rich-editor for the user. False if not empty. * @type bool $syntax_highlighting Whether to enable the rich code editor for the user. False if not empty. * @type bool $comment_shortcuts Whether to enable keyboard shortcuts for the user. Default false. * @type string $admin_color The color scheme for a user's admin screen. Default 'fresh'. * @type int|bool $use_ssl Whether to force SSL on the user's admin area. 0|false if SSL is * not forced. * @type bool $show_admin_bar_front Whether to show the admin bar on the front end for the user. * Default true. * } * * @param WP_User $user User object. * @param bool $update Whether the user is being updated rather than created. */ add_filter( 'insert_user_meta', 'smyles_custom_username_seq_verify', 10, 3 ); /** * Verify user was created, and then increase option value * * * @author Myles McNamara * * @param $meta * @param $user WP_User * @param $update * * @return mixed */ function smyles_custom_username_seq_verify( $meta, $user, $update ){ // Don't want to verify if this is just an update call if( ! $update && $user && $user->user_login ){ // Check what the last user num was stored as $last_user_num = get_option( 'smyles_custom_seq_usernames_last_id', 0 ); // Verify that user_login of the user that was created, matches what is supposed to be the next user_login if( (int) $last_user_num + 1 === (int) $user->user_login ){ // Update our option after verification update_option( 'smyles_custom_seq_usernames_last_id', (int) $user->user_login ); // Type casting to int causes 0000000001 to be 1 (trim leading zeros) } } return $meta; } add_action( 'cred_save_data', 'tssupp_cred_autologin', 10, 2 ); function tssupp_cred_autologin( $post_id, $form_data ){ // Login without email if ( 1194 == $form_data['id'] ) { $my_username = smyles_custom_username_seq_pre_user_login( $sanitized_user_login ); if ( !empty( $_POST['user_pass'] ) ) { $user = get_user_by( "login", $my_username ); $signon = array( 'user_login' => $user->user_login, 'user_password' => $_POST['user_pass'], 'remember' => true ); $login = wp_signon( $signon, false ); if ( is_wp_error($login) ) { error_log( $login->get_error_message() ); } } }; // Login with email if ( 3137 == $form_data['id'] ) { if ( !empty( $_POST['user_email'] ) && !empty( $_POST['user_pass'] ) ) { $user = get_user_by( "email", $_POST['user_email'] ); $signon = array( 'user_login' => $user->user_login, 'user_password' => $_POST['user_pass'], 'remember' => true ); $login = wp_signon( $signon, false ); if ( is_wp_error($login) ) { error_log( $login->get_error_message() ); } } }; }