Issue
I am creating a new User with wp_insert_user() function in an AJAX call. After that I need to add the phone number as custom field, so I need to use the wordpress hook user_register and I don't know how to use it.
add_action('wp_ajax_nopriv_register', 'register_user');
add_action('wp_ajax_register', 'register_user');
function registrar_cliente(){
if(isset($_POST['dataForPHP'])){
$phone = wp_filter_nohtml_kses($_POST['dataForPHP'][0]);
$name = wp_filter_nohtml_kses($_POST['dataForPHP'][1]);
$email = wp_filter_nohtml_kses($_POST['dataForPHP'][2]);
$userdata = [//adding data];
$user_id = wp_insert_user($userdata);
}
}
How can I use now do_action( 'user_register', int $user_id, array $userdata )
in order to insert $phone to the user in a custom field?
Solution
You can store the value of the custom field in user_meta.
add_action( 'wp_ajax_nopriv_register', 'register_user' );
add_action( 'wp_ajax_register', 'register_user' );
function register_user() {
$phone = wp_filter_nohtml_kses( $_POST['dataForPHP'][0] );
$name = wp_filter_nohtml_kses( $_POST['dataForPHP'][1] );
$email = wp_filter_nohtml_kses( $_POST['dataForPHP'][2] );
// $userdata = [adding data];
$user_id = wp_insert_user( $userdata );
$user_meta = update_user_meta( $user_id, 'phone_no', $phone );
if ( isset( $user_id ) ) {
echo 'User registered';
}
}
Code for adding extra fields in Edit User Section:
add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );
function extra_user_profile_fields( $user ) {
?>
<h3><?php _e( 'Extra profile information', 'blank' ); ?></h3>
<table class="form-table">
<tr>
<th><label for="phone_no"><?php _e( 'Phone Number' ); ?></label></th>
<td>
<input type="text" name="phone_no" id="phone_no"
value="<?php echo esc_attr( get_user_meta( $user->ID, 'phone_no', true ) ); ?>"
class="regular-text" /><br />
<span class="description"><?php _e( 'Please enter your phone number.' ); ?></span>
</td>
</tr>
</table>
<?php
}
Code for saving extra fields details in the database from the edit screen(If you want to change value from edit screen):
add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );
function save_extra_user_profile_fields( $user_id ) {
update_user_meta( $user_id, 'phone_no', $_POST['phone_no'] );
}
Answered By - Krunal Bhimajiyani Answer Checked By - Pedro (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.