Skip to content

Instantly share code, notes, and snippets.

@Spirecool
Last active April 21, 2021 13:51
Show Gist options
  • Select an option

  • Save Spirecool/17f9e3c3026e00f428bee04ac8bdb6ab to your computer and use it in GitHub Desktop.

Select an option

Save Spirecool/17f9e3c3026e00f428bee04ac8bdb6ab to your computer and use it in GitHub Desktop.
<?php
// add fields
add_action( 'woocommerce_after_checkout_billing_form', 'misha_select_field' );
add_action( 'woocommerce_after_order_notes', 'misha_subscribe_checkbox' );
// save fields to order meta
add_action( 'woocommerce_checkout_update_order_meta', 'misha_save_what_we_added' );
// select
function misha_select_field( $checkout ){
// you can also add some custom HTML here
woocommerce_form_field( 'contactmethod', array(
'type' => 'select', // text, textarea, select, radio, checkbox, password, about custom validation a little later
'required' => true, // actually this parameter just adds "*" to the field
'class' => array('misha-field', 'form-row-wide'), // array only, read more about classes and styling in the previous step
'label' => 'Preferred contact method',
'label_class' => 'misha-label', // sometimes you need to customize labels, both string and arrays are supported
'options' => array( // options for <select> or <input type="radio" />
'' => 'Please select', // empty values means that field is not selected
'By phone' => 'By phone', // 'value'=>'Name'
'By email' => 'By email'
)
), $checkout->get_value( 'contactmethod' ) );
// you can also add some custom HTML here
}
// checkbox
function misha_subscribe_checkbox( $checkout ) {
woocommerce_form_field( 'subscribed', array(
'type' => 'checkbox',
'class' => array('misha-field form-row-wide'),
'label' => ' Subscribe to our newsletter.',
), $checkout->get_value( 'subscribed' ) );
}
// save field values
function misha_save_what_we_added( $order_id ){
if( !empty( $_POST['contactmethod'] ) )
update_post_meta( $order_id, 'contactmethod', sanitize_text_field( $_POST['contactmethod'] ) );
if( !empty( $_POST['subscribed'] ) && $_POST['subscribed'] == 1 )
update_post_meta( $order_id, 'subscribed', 1 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment