Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Edwynn/601f55799866f10e994e92ffadf740a6 to your computer and use it in GitHub Desktop.
Save Edwynn/601f55799866f10e994e92ffadf740a6 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;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment