Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dannyconnolly/05695195cca6ab5ae31f to your computer and use it in GitHub Desktop.
Save dannyconnolly/05695195cca6ab5ae31f to your computer and use it in GitHub Desktop.
Add custom field to woocommerce checkout.
/**
* Add vehicle registration field to the checkout page
*/
add_action( 'woocommerce_after_order_notes', 'car_registration_checkout_field' );
function car_registration_checkout_field( $checkout ) {
echo '<div id="car_registration_checkout_field"><h2>' . __('Car Registration') . '</h2>';
woocommerce_form_field( 'car_registration_no', array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'label' => __('Car Registration'),
'placeholder' => __('Please enter your Car Registration No.'),
'required' => true,
), $checkout->get_value( 'car_registration_no' ));
echo '</div>';
}
/**
* Process the checkout
*/
add_action('woocommerce_checkout_process', 'car_registration_checkout_field_process');
function car_registration_checkout_field_process() {
// Check if the field is set, if not then show an error message.
if ( ! $_POST['car_registration_no'] )
wc_add_notice( __( 'Please enter your Car Registration No.' ), 'error' );
}
/**
* Update the order meta with field value
*/
add_action( 'woocommerce_checkout_update_order_meta', 'car_registration_checkout_field_update_order_meta' );
function car_registration_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST['car_registration_no'] ) ) {
update_post_meta( $order_id, 'Car Registration No', sanitize_text_field( $_POST['car_registration_no'] ) );
}
}
/**
* Add the field to order emails
**/
add_filter( 'woocommerce_email_order_meta_keys', 'car_registration_meta_keys' );
function car_registration_meta_keys() {
if (get_post_meta( get_the_ID(), 'Car Registration No')) {
echo 'Car Registration No: ' . get_post_meta( get_the_ID(), 'Car Registration No', true) . '<br />';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment