Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save viniciusrtf/e8daaa2ae753f2242127 to your computer and use it in GitHub Desktop.
Save viniciusrtf/e8daaa2ae753f2242127 to your computer and use it in GitHub Desktop.
WooCommerce: Adding custom fields to checkout, order/user meta and emails
<?php
/** ###################################################### *
* *
* Adding custom fields to checkout, order/user meta and emails *
* *
* ####################################################### */
/**
* Add the 'Profissão' field to the checkout
**/
add_action('woocommerce_after_order_notes', 'billing_position_field');
function billing_position_field( $checkout ) {
echo '<div id="billing_position_field">';
woocommerce_form_field( 'billing_position', array(
'type' => 'text',
'class' => array('form-row-wide'),
'label' => __('Profiss&atilde;o'),
'placeholder' => __('Profiss&atilde;o'),
), $checkout->get_value( 'billing_position' ));
echo '</div>';
echo '<script type="text/javascript">jQuery(document).ready(function() { jQuery("#billing_position_field").detach().insertAfter("#billing_cnpj_field"); });</script>';
}
/**
* Process the checkout
**/
add_action('woocommerce_checkout_process', 'billing_position_field_process');
function billing_position_field_process() {
global $woocommerce;
// Check if set, if its not set add an error. This one is only requite for companies
if ($_POST['billing_company'])
if (!$_POST['billing_position'])
$woocommerce->add_error( __('Por favor, digite sua profiss&atilde;o.') );
}
/**
* Update the user meta with field value
**/
add_action('woocommerce_checkout_update_user_meta', 'billing_position_field_update_user_meta');
function billing_position_field_update_user_meta( $user_id ) {
if ($user_id && $_POST['billing_position']) update_user_meta( $user_id, 'billing_position', esc_attr($_POST['billing_position']) );
}
/**
* Update the order meta with field value
**/
add_action('woocommerce_checkout_update_order_meta', 'billing_position_field_update_order_meta');
function billing_position_field_update_order_meta( $order_id ) {
if ($_POST['billing_position']) update_post_meta( $order_id, 'Profiss&atilde;o', esc_attr($_POST['billing_position']));
}
/**
* Add the field to order emails
**/
add_filter('woocommerce_email_order_meta_keys', 'billing_position_field_order_meta_keys');
function billing_position_field_order_meta_keys( $keys ) {
$keys[] = 'Profiss&atilde;o';
return $keys;
}
?>
@davemtb2
Copy link

I've added several fields using this method and all is well but the fields are NOT included when I 'Resend order emails' from the Order Options panel on the Edit Order page in the admin.

Which filter do I need to add to have these fields included with all emails?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment