Code snippets to make new contacts work
Courtesy of ChatGPT!!
<?php
add_filter('civicrm_groups_sync_user_id_get_by_contact_id', 'my_civicrm_create_user', 10, 2);
function my_civicrm_create_user($user_id, $contact_id) {
if (!$user_id) {
// Get Contact data
$contact = civicrm_api3('Contact', 'get', [
'id' => $contact_id,
'return' => ['first_name', 'last_name', 'email'],
]);
// Prepare params for creating a new WordPress User
$username = strtolower($contact['values'][$contact_id]['first_name'].$contact['values'][$contact_id]['last_name']);
$email = $contact['values'][$contact_id]['email'];
$password = wp_generate_password();
// Create a new WordPress User
$user_id = wp_create_user($username, $password, $email);
// Return the User ID
if (!is_wp_error($user_id)) {
return $user_id;
}
}
return $user_id;
}
Note: This code assumes that the CiviCRM API is already available in the WordPress environment. You might need to include the CiviCRM API wrapper file or use a CiviCRM plugin to make it available.
add_filter('civicrm_groups_sync_contact_id_get_by_user_id', 'my_civicrm_create_contact', 10, 2);
function my_civicrm_create_contact($contact_id, $user_id) {
if (!$contact_id) {
// Get user data
$user = get_userdata($user_id);
// Prepare params for creating a new CiviCRM Contact
$params = [
'contact_type' => 'Individual',
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->user_email,
];
// Create a new CiviCRM Contact
$result = civicrm_api3('Contact', 'create', $params);
// Return the Contact ID
if ($result['is_error'] == 0) {
$contact_id = $result['id'];
}
}
return $contact_id;
}
Note: This code assumes that the CiviCRM API is already available in the WordPress environment. You might need to include the CiviCRM API wrapper file or use a CiviCRM plugin to make it available.
Edited by Phil McKerracher