Skip to content

Instantly share code, notes, and snippets.

@zainaali
Created September 22, 2018 11:32
Show Gist options
  • Save zainaali/c068086d0ce2fe3f720f36f892e897f5 to your computer and use it in GitHub Desktop.
Save zainaali/c068086d0ce2fe3f720f36f892e897f5 to your computer and use it in GitHub Desktop.
Create Custom Billing Field and pre fill Auto fill checkout default filed and custom filed from user data saved in Woocommerce session
/**
* C.1. Custom Billing Field
*/
add_filter( 'woocommerce_billing_fields' , 'wc_custom_fields' );
function wc_custom_fields( $fields ) {
$fields['billing_reservationcode'] = array(
'type' => 'text',
'required' => true,
'class' => array('reservationcode'),
'label' => 'Reservation Code',
'label_class' => 'reservation-code'
);
return $fields;
}
add_action( 'template_redirect', 'set_custom_data_wc_session' );
function set_custom_data_wc_session () {
if ( isset( $_GET['fname'] ) ) {
$fname = isset( $_GET['fname'] ) ? esc_attr( $_GET['fname'] ) : '';
}
if (isset( $_GET['lname'] )) {
$lname = isset( $_GET['lname'] ) ? esc_attr( $_GET['lname'] ) : '';
}
if (isset( $_GET['email'] )) {
$email = isset( $_GET['email'] ) ? esc_attr( $_GET['email'] ) : '';
}
if (isset( $_GET['rcode'] )) {
$rcode = isset( $_GET['rcode'] ) ? esc_attr( $_GET['rcode'] ) : '';
}
// Set the session data
WC()->session->set( 'custom_data', array( 'fname' => $fname, 'lname' => $lname, 'email' => $email, 'rcode' => $rcode) );
}
// Autofill checkout fields from user data saved in Woocommerce session
add_filter( 'woocommerce_billing_fields' , 'prefill_billing_fields', 99999 );
function prefill_billing_fields ( $address_fields ) {
// Get the session data
$data = WC()->session->get('custom_data');
// First Name
if( isset($data['fname']) && ! empty($data['fname']) )
$address_fields['billing_first_name']['default'] = $data['fname'];
// Last Name
if( isset($data['lname']) && ! empty($data['lname']) )
$address_fields['billing_last_name']['default'] = $data['lname'];
//var_dump( $data['lname']);exit;
// Email
if( isset($data['email']) && ! empty($data['email']) )
$address_fields['billing_email']['default'] = $data['email'];
// reservationcode
if( isset($data['rcode']) && ! empty($data['rcode']) )
$address_fields['billing_reservationcode']['default'] = $data['rcode'];
// echo'<pre>';
// var_dump($address_fields);
return $address_fields;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment