Created
August 8, 2019 15:40
-
-
Save markhowellsmead/524453af6ca75d758eff5876bfcc87d6 to your computer and use it in GitHub Desktop.
Create user from Gravity Forms submission (incomplete!)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This is only part of a Package for WordPress | |
* Call function from within a master function which has been hooked to gform_after_submission | |
*/ | |
private function userFromSubmission($entry, $form) | |
{ | |
$submitted_email = ''; | |
$user = null; | |
foreach ($form['fields'] as $field) { | |
if ($field->isUserEmail) { | |
$submitted_email = rgar($entry, $field->id, null); | |
} | |
} | |
if (!empty($submitted_email) && ($existing_user = get_user_by('email', $submitted_email))) { | |
return $existing_user; | |
} | |
if (!$user) { | |
$first_name = ''; | |
$last_name = ''; | |
// $phone = ''; | |
$address = []; | |
foreach ($form['fields'] as $field) { | |
if ($field->isUserEmail) { | |
$submitted_email = rgar($entry, $field->id, null); | |
} | |
if ($field->isUserFirstName) { | |
$first_name = rgar($entry, $field->id, null); | |
} | |
if ($field->isUserLastName) { | |
$last_name = rgar($entry, $field->id, null); | |
} | |
// if ($field->isUserPhone) { | |
// $phone = (int) rgar($entry, $field->id, null); | |
// } | |
if ($field->isUserAddress) { | |
$address = (array) rgar($entry, $field->id, null); | |
} | |
} | |
$user_login = $submitted_email; | |
if (strlen($user_login) > 60) { | |
$user_login = substr($user_login, 0, 60); | |
} | |
$display_name = implode(' ', [$first_name, $last_name]); | |
if (strlen($display_name) > 60) { | |
$display_name = substr($display_name, 0, 60); | |
} | |
$user_id = wp_insert_user([ | |
'first_name' => $first_name, | |
'last_name' => $last_name, | |
'display_name' => $display_name, | |
'user_login' => $user_login, | |
'user_email' => $submitted_email, | |
'user_pass' => wp_generate_password(8, false) | |
]); | |
if (is_wp_error($user_id)) { | |
if (defined('WP_DEBUG') && WP_DEBUG === true) { | |
throw new Exception(sprintf( | |
__('Forms::userFromSubmission - unable to create user - %s', 'sht'), | |
$user_id->get_error_message() | |
)); | |
} | |
return false; | |
} | |
$user = get_user_by('id', $user_id); | |
if (!empty($address)) { | |
foreach ($address as $key => $value) { | |
update_user_meta($user->ID, $key, $value); | |
} | |
} | |
// Send a new registration confirmation to user and website admin | |
wp_new_user_notification($user->ID, null, 'both'); | |
return $user; | |
} | |
return $user; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment