Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hazratbilal0079/d58658144e1fd85eb670d687a05747d9 to your computer and use it in GitHub Desktop.
Save hazratbilal0079/d58658144e1fd85eb670d687a05747d9 to your computer and use it in GitHub Desktop.
Register or Invite New User with Random Password and Custom Role from Frontend with PHP Hook or Code Snippet
--Hook Name
registernewuseras
--PHP Hook
add_action( 'jet-form-builder/custom-action/registernewuseras', function( $request, $action_handler ) {
$username = sanitize_user($_POST['emailaddress']);
$email = sanitize_email($_POST['emailaddress']);
$first_name = sanitize_text_field($_POST['firstname']);
$last_name = sanitize_text_field($_POST['lastname']);
$password = sanitize_text_field($_POST['Password']);
$phone_number = sanitize_text_field($_POST['phone']);
$role = sanitize_text_field($_POST['user_role_as']);
$user_id = wp_create_user($email, $password, $email);
if (is_wp_error($user_id)) {
// Handle registration error here
echo 'User registration error: ' . $user_id->get_error_message();
} else {
$user_id_role = new WP_User($user_id);
$user_id_role->set_role($role);
update_user_meta($user_id, 'first_name', $first_name);
update_user_meta($user_id, 'last_name', $last_name);
update_user_meta($user_id, 'phone', $phone_number);
}
}, 10, 2 );
--Script to assign Random password to the Password field which css class is 'usser_password'
<script src="https://code.jquery.com/jquery-3.6.0.min.js">
</script>
<script>
jQuery(document).ready(function($) {
// Generate a random password
var generatePassword = (
length = 20,
wishlist = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$'
) =>
Array.from(crypto.getRandomValues(new Uint32Array(length)))
.map((x) => wishlist[x % wishlist.length])
.join('');
// Check if the password field exists
if ($(".usser_password").length) {
// Assign the generated password to the password field
$(".usser_password").val(generatePassword());
console.log("Password field found and value assigned.");
} else {
console.log("Password field not found.");
}
});
</script>
For more information video link:
https://youtu.be/BsM-7hgKX_o
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment