Last active
June 27, 2024 11:30
-
-
Save gicolek/45b90449eeea73295c1a to your computer and use it in GitHub Desktop.
A sample code, which fires before the form was submitted and creates a new user account.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // remember - the suffix of the hook should contain specific form id! | |
| add_action( "gform_pre_submission_3", "wp_doin_pre_submission" ); | |
| function wp_doin_pre_submission($form) { | |
| // get the values entered by the user during the form submission | |
| // note: the input_{number} may be different in your case, make sure to double check the id of your field | |
| // and swap it if needed | |
| $username = esc_attr( $_POST['input_1'] ); | |
| $email = sanitize_email( $_POST['input_3'] ); | |
| // if we're doing a cron job let's forget about it | |
| if ( defined( 'DOING_CRON' ) || isset( $_GET['doing_wp_cron'] ) ) | |
| return; | |
| // let's check if a user with given name exists | |
| // we're already doing that in the form validation, however it's a good practice to redo the check here | |
| $user_id = username_exists( $username ); | |
| // if the user doesn't exist and his email is not associated with any other account then, move forward | |
| if ( !$user_id and email_exists( $email ) == false ) { | |
| // let's generate a passowrd | |
| $random_password = wp_generate_password( $length = 12, false ); | |
| // let's create a new user | |
| $user_id = wp_create_user( $name, $random_password, $email ); | |
| // let's notify the new user | |
| wp_new_user_notification( $user_id, $random_password ); | |
| } else { | |
| // validation failed | |
| return; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment