Syncing user registrations in Amelia and WordPress
-
When a booking is made in the Amelia plugin, a WordPress user with the “Amelia Customer” role is automatically created. There are no issues with that.
But when registering in WordPress, no user is created in the Amelia plugin. This is natural if there is no booking.
I want to set it up so that the user doesn’t have to register twice: once when registering in WordPress and again when making a booking. Only one registration is needed for convenience.
add_action('user_register', 'custom_amelia_registration_save', 10, 1);
function custom_amelia_registration_save($user_id) {
global $wpdb;
// Get the WordPress user by ID
$wp_user = get_user_by('ID', $user_id);
if (!$wp_user) {
error_log('User with ID ' . $user_id . ' not found');
return;
}
// Check if the user has the 'amelia-customer' role
if (!in_array('amelia-customer', $wp_user->roles, true)) {
error_log('User ID ' . $user_id . ' does not have the amelia-customer role');
return;
}
// Retrieve the WordPress table prefix
$table_prefix = $wpdb->prefix;
$amelia_users_table = $table_prefix . 'amelia_users';
// Secure query to check if the user already exists in Amelia (using prepare() to prevent SQL injection)
$amelia_user_id = $wpdb->get_var(
$wpdb->prepare(
"SELECT id FROM {$amelia_users_table} WHERE email = %s",
$wp_user->user_email
)
);
// If the user is not found in Amelia, create a new record
if (!$amelia_user_id) {
// Prepare data for insertion: use first name if available, otherwise use username
$first_name = !empty($wp_user->first_name) ? $wp_user->first_name : $wp_user->user_nicename;
// Prepare data for insertion: use last name if available, otherwise use username
$last_name = !empty($wp_user->last_name) ? $wp_user->last_name : $wp_user->user_nicename;
// Insert data into Amelia users table using the safe $wpdb->insert() method
$result = $wpdb->insert(
$amelia_users_table,
array(
'type' => 'customer',
'status' => 'visible',
'externalId' => $user_id,
'firstName' => $first_name,
'lastName' => $last_name,
'email' => $wp_user->user_email,
),
array('%s', '%s', '%d', '%s', '%s', '%s') // Specify data types for each field
);
// Log the result of the insertion operation
if (false === $result) {
error_log('Amelia user insertion failed: ' . $wpdb->last_error);
} else {
error_log('Amelia user successfully created with ID: ' . $wpdb->insert_id);
}
} else {
// Log that the user already exists in Amelia
error_log('User already exists in Amelia (ID: ' . $amelia_user_id . ')');
}
}Unfortunately, my code isn’t working. I can’t figure out what the problem is. I hope you can help!
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
You must be logged in to reply to this topic.