WordPress user creation via custom PHP function


In the code below, we are registering the user via Ajax request and receiving a JSON reply from the script.
The code also checks and validates the sent email address against the user information already in the database.

You can place the code in your theme’s functions file and send the form via POST to admin-ajax.

Code Below:

add_action('wp_ajax_yourown_register_action_custom', 'custom_register_custom');
add_action('wp_ajax_nopriv_yourown_register_action_custom', 'custom_register_custom');

function custom_register_custom(){
$output = array(
‘success’ => false, // did the submission work?
‘errors’ => array(), // what errors were encountered on the field elements
‘redirect_to’ => ‘#’, // where should we go?
‘message’ => ”, // what message should be provided?
);

$email = $_POST[‘user_email’];

if(email_exists($email)){ // — inbuilt wordpress function
$output = array(
‘success’ => false, // did the submission work?
‘errors’ => array([__(‘Email already exists!’)]), // what errors were encountered on the field elements
‘redirect_to’ => ‘#’, // where should we go?
‘message’ => __(‘Email already exists!’), // what message should be provided?
);
print json_encode( $output );
exit();
}

$user_data = [
‘user_pass’ => $_POST[‘user_pass’],
‘user_login’=> $email,
‘user_email’=> $email,
‘first_name’=> $_POST[‘first_name’],
‘last_name’ => $_POST[‘last_name’],
‘display_name’ => $_POST[‘display_name’]
];

$user_id = wp_insert_user( $user_data ); // — Create User using wordpress wp_insert_user()

if ( ! is_wp_error( $user_id ) ) {
$wp_user_object = new WP_User($user_id);
$wp_user_object->set_role(‘frontend_vendor’);

try{
$email_validation_code = rand( 100000000, 999999999 );
$email_validation_link = get_site_url().’/validate-email/?ruid=’.base64_encode($user_id).’&validation=’.base64_encode($email_validation_code);

add_user_meta($user_id, ’email_validated’, “0”, 1);
add_user_meta($user_id, ’email_validation_code’, $email_validation_code, 1);

wp_mail( $email, ‘Confirm your email address’, ‘Dear ‘.$_POST[‘first_name’].’
Confirm your email address by clicking the link below : ‘.$email_validation_link, $headers );
} catch ( Exception $E ){
wp_mail( ‘developers_email@domain.tld’, ‘Error’ , print_r( $E, true ));
}

$output[‘success’] = true;
$output[‘errors’][] = __( ‘Success : Your account has been created. Please verify your email.’ );
$output[‘message’] = __( ‘Success : Your account has been created. Please verify your email.’ );
} else {
$output[‘success’] = false;
$output[‘errors’][] = __( ‘Error creating user.’ );
$output[‘message’] = __( ‘Error creating user.’ );
}


print json_encode( $output );
exit();
}

Read more at https://www.aadilprabhakar.in/category/web-development/