Created
June 17, 2015 09:52
-
-
Save dannyconnolly/05695195cca6ab5ae31f to your computer and use it in GitHub Desktop.
Add custom field to woocommerce checkout.
This file contains hidden or 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
/** | |
* 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