I have created an extra Woocommerce field on the product page, so that the customer could include extra information to their order. I need that same data included in the order, so that the shop admin, as well as the customer, would be able to see it on their cart details and in the final order details as well.
Here's the code I used so far:
function get_user_input() {
global $product;
$render_html = ' ';
if ( $product->get_meta( '_drawer_type' ) != 'non_drawer' ) {
$render_html = '<div class="drawer-input-container">';
$render_html .= wp_nonce_field( 'wcd-add-to-cart', 'wcdprdcartnonce', false, false );
$render_html .= '<input type="number" name="drawer_height" label="Drawer Dimension: ">';
$render_html .= '</div>';
echo $render_html;
}
else {
return;
}
}
add_action( 'woocommerce_before_add_to_cart_button', 'get_user_input' );
function add_cart_drawer_data( $cart_item_data, $product_id, $variation_id ) {
if ( ! isset( $_POST['wcdprdcartnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( (string) $_POST['wcdprdcartnonce'] ) ), 'wcd-add-to-cart' ) ) {
return $cart_item_data;
}
$dheight = filter_input( INPUT_POST, 'drawer_height' );
if ( !empty( $dheight ) ) {
$cart_item_data['drawer_height'] = $dheight;
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_drawer_data', 10, 3 );
function add_order_drawer_data( $item, $cart_item_key, $values, $order ) {
if (! empty( $values['drawer_height'] ) ) {
$item->add_meta_data( __( 'Drawer Height', 'woocommerce' ), $values['drawer_height'] );
}
}
add_filter( 'woocommerce_checkout_create_order_line_item', 'add_order_drawer_data', 10, 4 );
'''
What are the next steps? Which action hooks must be used? Maybe someone could help me get on the right track...