[ad_1]
I have created a WordPress site where users register on the front-end and add information about themselves. On registration I am forcing the user_nicename
to be name-surname. I am then automatically creating 2 custom post types that act as profile pages for the new users. I am using the user_nicename
as the title of both.
The problem is obviously if two people register with the same name.
So I would like to check the database before the user_nicename
is updated to check if it already exists. If it does I would like to add an integer (in sequence) to the end of the user_nicename
.
For instance:
- John-Smith
- John-Smith-2
- John-Smith-3
- Etc.
The code I have tried is as follows. The exists_in_database piece is clearly where it goes wrong. Any help would be much appreciated. Thank you!
add_action( 'user_registration_after_register_user_action', 'ur_insert_username', 1, 3 );
function ur_insert_username( $valid_form_data, $form_id, $user_id ) {
global $wpdb;
$firstname = isset( $valid_form_data['first_name'] ) ? $valid_form_data['first_name']->value : '';
$lastname = isset( $valid_form_data['last_name'] ) ? $valid_form_data['last_name']->value : '';
$custom_nicename = sanitize_title_with_dashes( $firstname . '-' . $lastname);
$i = 1;
do {
//Check in the database here
$exists = exists_in_database($custom_nicename);
if($exists) {
$i++;
$name = $first_name . $i;
}
} while($exists);
$wpdb->update(
$wpdb->users,
['user_nicename' => $custom_nicename],
['ID' => $user_id]
);
{
$user_post_athlete = array(
'post_title' => $custom_nicename,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'athlete', // <- change to your cpt
'post_author' => $user_id
);
$user_post_rivalry = array(
'post_title' => $custom_nicename,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'rivalry', // <- change to your cpt
'post_author' => $user_id
);
// Insert the post into the database
$post_id = wp_insert_post( $user_post_athlete );
$post_id = wp_insert_post( $user_post_rivalry );
}
}
[ad_2]