On a woocommerce single page product, I have created a custom field. And i want its value to be stored in the order meta, when the order is validated. After several hours of research i have not been able to find any solution to come to the end ! But i'm sure i'm pretty close to it...
Here is my actual code:
// create the custom field
add_action( 'woocommerce_before_add_to_cart_button', 'add_fields_before_add_to_cart', 100 );
function add_fields_before_add_to_cart($post) {
?>
<select class="selectpicker" name="premiere_box_abo" id="premiere_box_abo">
<option value="Septembre 2018">Septembre 2018</option>
<option value="Octobre 2018">Octobre 2018</option>
</select>
<?php
}
// Store custom field
function save_my_custom_checkout_field( $cart_item_data, $product_id ) {
if( isset( $_POST['premiere_box_abo'] ) ) {
$cart_item_data[ 'premiere_box_abo' ] = $_POST['premiere_box_abo'];
/* below statement make sure every add to cart action as unique line item */
$cart_item_data['unique_key'] = md5( microtime().rand() );
}
return $cart_item_data;
}
add_action( 'woocommerce_add_cart_item_data', 'save_my_custom_checkout_field', 10, 2 );
// Render meta on cart and checkout
function render_meta_on_cart_and_checkout( $cart_data, $cart_item = null ) {
$custom_items = array();
/* Woo 2.4.2 updates */
if( !empty( $cart_data ) ) {
$custom_items = $cart_data;
}
if( isset( $cart_item['premiere_box_abo'] ) ) {
$custom_items[] = array( "name" => '1e box abonnement', "value" => $cart_item['premiere_box_abo'] );
}
return $custom_items;
}
add_filter( 'woocommerce_get_item_data', 'render_meta_on_cart_and_checkout', 10, 2 );
// Display as order meta
add_action( 'woocommerce_add_order_item_meta', 'my_field_order_meta_handler', 1, 3 );
function my_field_order_meta_handler( $item_id, $values ) {
if( isset( $values['premiere_box_abo'] ) ) {
wc_add_order_item_meta( $item_id, "1e box abonnement", $values['premiere_box_abo'] );
}
}
// 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['premiere_box_abo'] ) ) {
update_post_meta( $order_id, 'premiere_box_abo', sanitize_text_field( $_POST['premiere_box_abo'] ) );
}
}
And here is What I have so far:
That is what I would like :
How can I save this custom field data as order meta data to make appear the value in "custom fields" meta box.
Any help is appreciated.