Wordpress - Woocommerce
What I try to do:
- Add some custom fields in the Checkout page.
- Also, send the value of these fields to my email when receiving a new order.
This is what I did, but failed:
I follow the tutorial here: http://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/
Everything goes right, I created the fields successfully and they appear in the order setting page:
add_action( 'woocommerce_after_order_notes', 'my_checkout_fields' );
function my_checkout_fields( $checkout ) {
echo '<div id="my_checkout_fields"><h2>' . __('My Heading') . '</h2>';
woocommerce_form_field( 'my_field', array(
'type' => 'select',
'options' => array(
'option_1' => 'My Option 1',
'option_2' => 'My Option 2'
),
'clear' => false,
'class' => array('form-row-wide'),
'label' => __('Whatever')
), $checkout->get_value( 'my_field' ));
echo '</div>';
}
/**
* 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 ( ! empty( $_POST['my_field'] ) ) {
update_post_meta( $order_id, 'My Field', sanitize_text_field( $_POST['my_field'] ) );
}
}
}
Then, I tried to add them into the email order meta as shown at the 'Lesson 4' section in the tutorial:
add_filter('woocommerce_email_order_meta_keys', 'my_custom_checkout_field_order_meta_keys');
function my_custom_checkout_field_order_meta_keys( $keys ) {
$keys[] = 'my_field';
return $keys;
}
But, the custom fields do not appear in the email sent.
I have also tried to test it by doing this in the email template file:
<p><?php echo $order->my_field; ?></p>
Nothing is printed in the email.
Solution please. Thanks in advance.