Hi Salim,
Thank you for waiting.
I was able to make this work on my test website, using the following steps:
1. In a custom post type "User Applications", I added these custom fields
- user-email (email type)
- user-first-name (single line type)
- user-last-name (single line type)
- user-created (single line type)
- application-status (radio type)
--- field options
-----Under Review (value '1', default)
-----Accpeted (value '2')
-----Rejected (value '3')
Note: The "user-created" will help in keeping track of whether a user has been created already for a particular "User Application" post or not.
2. Next, I created an edit form for "User Application" and only included the "application-status" field and the submit button.
3. After that, I used the "cred_save_data" hook ( https://toolset.com/documentation/programmer-reference/cred-api/#cred_save_data ) and the "wp_insert_user" function ( https://developer.wordpress.org/reference/functions/wp_insert_user/ ) to programmatically add a new user, when that form is submitted with Accpeted (value '2') option:
add_action( 'cred_save_data', 'custom_user_author_update', 10, 2 );
function custom_user_author_update( $post_id, $form_data ) {
if ($form_data['id']==12345) {
// get value of field to check if user has been created already through user-created field
$user_created = get_post_meta($post_id, 'wpcf-user-created', true);
// if field value is approved and user is not already created
if( ($_POST['wpcf-application-status'] == '2') && ($user_created != 'yes') ) {
$user_name = get_post_meta($post_id, 'wpcf-user-email', true);
$user_email = get_post_meta($post_id, 'wpcf-user-email', true);
$user_fname = get_post_meta($post_id, 'wpcf-user-first-name', true);
$user_lname = get_post_meta($post_id, 'wpcf-user-last-name', true);
$userdata = array(
'user_login' => $user_email,
'user_pass' => NULL, // When creating an user, `user_pass` is expected.
'user_email' => $user_email,
'first_name' => $user_fname,
'last_name' => $user_lname,
'role' => 'subscriber'
);
// insert new user
$user_id = wp_insert_user( $userdata ) ;
// On success send new user notification to user and admin and update yes in the user-created custom field
if ( ! is_wp_error( $user_id ) ) {
wp_new_user_notification( $user_id, null, 'both' );
update_post_meta( $post_id, 'wpcf-user-created', 'yes' );
}
}
}
}
Please replace "12345" with your actual edit form's ID and adjust the code as per your custom fields.
Note: The custom code examples from our forum are shared to get you started in the right direction. You're welcome to adjust them as needed and for more personalized customization assistance, you can consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/
regards,
Waqar