Created
March 11, 2018 15:19
-
-
Save woogists/931aa497fbbdc1061507a61798af5f7f to your computer and use it in GitHub Desktop.
[Customizing checkout fields using actions and filters] Add custom WooCommerce checkout field to emails
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
/* To use: | |
1. Add this snippet to your theme's functions.php file | |
2. Change the meta key names in the snippet | |
3. Create a custom field in the order post - e.g. key = "Tracking Code" value = abcdefg | |
4. When next updating the status, or during any other event which emails the user, they will see this field in their email | |
*/ | |
add_filter('woocommerce_email_order_meta_keys', 'my_custom_order_meta_keys'); | |
function my_custom_order_meta_keys( $keys ) { | |
$keys[] = 'Tracking Code'; // This will look for a custom field called 'Tracking Code' and add it to emails | |
return $keys; | |
} |
Hi guys,
can you share the right code to use?Is not really clear for me.
Thanks.
x2
Full code for adding custom field by product ID, then displaying field value on the order edit page, and then adding to the emails.
* Add fields to the checkout page based on products in cart.
*
* @how-to https://remicorson.com/?p=7871
* @author Remi Corson
* @testedwith WooCommerce 3.4.0
*/
add_action( 'woocommerce_checkout_fields', 'woo_add_conditional_checkout_fields' );
function woo_add_conditional_checkout_fields( $fields ) {
foreach( WC()->cart->get_cart() as $cart_item ){
$product_id = $cart_item['product_id'];
if( $product_id == 947 ) {
$fields['billing']['billing_X'] = array(
'label' => __('Billing X, 'woocommerce'),
'placeholder' => _x('', 'placeholder', 'woocommerce'),
'required' => true,
'class' => array('form-row-wide'),
'clear' => true
);
}
}
// Return checkout fields.
return $fields;
}
/**
* Display field value on the order edit page
*/
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
function my_custom_checkout_field_display_admin_order_meta($order){
echo '<p><strong>'.__('Billing X').':</strong> ' . get_post_meta( $order->get_id(), '_billing_X', true ) . '</p>';
}
/**
* Add a custom field (in an order) to the emails
*/
add_filter( 'woocommerce_email_order_meta_fields', 'custom_woocommerce_email_order_meta_fields', 10, 3 );
function custom_woocommerce_email_order_meta_fields( $fields, $sent_to_admin, $order ) {
$fields['billing_X'] = array(
'label' => __( 'Billling X' ),
'value' => get_post_meta( $order->id, '_billing_X', true ),
);
return $fields;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi guys,
can you share the right code to use?
Is not really clear for me.
Thanks.