Skip to content

Instantly share code, notes, and snippets.

@jondcampbell
Forked from mikejolley/gist:1604009
Last active August 29, 2015 14:05
Show Gist options
  • Save jondcampbell/6fce0904461dd21d118e to your computer and use it in GitHub Desktop.
Save jondcampbell/6fce0904461dd21d118e to your computer and use it in GitHub Desktop.
Add a text field to woocommerce checkout, save the field data to user meta and order meta. Does not make the user meta show up in profile editor.
/**
* Add the field to the checkout
**/
add_action('woocommerce_after_order_notes', 'my_custom_checkout_field');
function my_custom_checkout_field( $checkout ) {
echo '<div id="custom_checkout_fields"><h3>'.__('Member Listing Profile').'</h3>';
/**
* Output the field.
*
**/
woocommerce_form_field( 'organization', array(
'type' => 'text',
'class' => array('organization form-row-wide'),
'label' => __('Organization'),
'placeholder' => __('Organization Name'),
), $checkout->get_value( 'organization' ));
echo '</div>';
}
/**
* Process the checkout
**/
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
global $woocommerce;
// Check if set, if its not set add an error.
if (!$_POST['organization'])
$woocommerce->add_error( __('Please enter your Organization Name.') );
}
/**
* Update the user meta with field value
**/
add_action('woocommerce_checkout_update_user_meta', 'my_custom_checkout_field_update_user_meta');
function my_custom_checkout_field_update_user_meta( $user_id ) {
if ($user_id && $_POST['organization']) update_user_meta( $user_id, 'organization', esc_attr($_POST['organization']) );
// check and make sure the stored value matches $_POST['organization']
if ( get_user_meta($user_id, 'organization', true ) != esc_attr($_POST['organization']) ) wp_die(' We could not save your organization');
}
/**
* Update the order meta with field value
**/
add_action('woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta');
function my_custom_checkout_field_update_order_meta( $order_id ) {
if ($_POST['organization']) update_post_meta( $order_id, 'Organization', esc_attr($_POST['organization']));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment