I want to be able to collect the first name and last name on the booking form.
By default the first name and last name are hidden when a user is already logged in. However, we have many users for whom we don’t have the first name and last name fields.
How can I make first and last name required fields on event booking forms?
Thanks
Dan
Dan Brady
Hi Dan,
As you’ve noted the name field is removed for logged-in users. He’s a snippet which will re-add it back in. I’ve left so that it will always appear for logged-in users, but you may want to adjust it slightly so it only appears if the user does not have a first and/or last name stored.
This should go in a custom plug-in, but will also work in a theme’s functions.php:
<?php
/**
* Add the removed name fields if the user is logged-in.
*/
add_action( 'eventorganiser_event_booking_form_render', function( $form ) {
if( is_user_logged_in() && !$form->get_element( 'name' ) ){
$current_user = wp_get_current_user();
$element = EO_Booking_Form_Element_Factory::create( array(
'id' => 'name',
'type' => 'name',
'field_name' => 'name',
'required' => true,
'label' => __( 'Name', 'eventorganiserp' ),
'value' => array(
'fname' => $current_user->user_firstname,
'lname' => $current_user->user_lastname,
)
) );
$form->add_element( $element, array( 'at' => 0 ) );
}
} );
/**
* Currently, if the user is logged-in, the booking form will forcebly
* set the name fields to that of the logged-in user. So we update the
* user's name before that happens.
*/
add_action( 'eo_booking_form_submission', function( $raw_data, $form_id, $form ) {
if( is_user_logged_in() && $form->get_element( 'name' ) ){
$name = $form->get_element( 'name' );
global $current_user;
$current_user = wp_get_current_user();
$current_user->user_firstname = $name->get_value( 'fname' );
$current_user->user_lastname = $name->get_value( 'lname' );
}
}, 10, 3 );
/**
* The booking form has been validated. We now update the database with the user's names
*/
add_action( 'eventorganiser_process_booking_form_submission', function( $form ) {
if( is_user_logged_in() && $form->get_element( 'name' ) ){
$name = $form->get_element( 'name' );
wp_update_user( array(
'ID' => get_current_user_id(),
'first_name' => $name->get_value( 'fname' ),
'last_name' => $name->get_value( 'lname' ),
) );
}
} );
Stephen Harris