Hello,
I would like to add a custom product field in the list of products in the order woocommerce.
This my code but doesn't work :
/**
* Add custom meta to order
*/
function checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
if( isset( $values['wpcf-numero-disque'] ) ) {
$item->add_meta_data(__( 'Disque :' ),$values['wpcf-numero-disque'],true);
}
}
add_action( 'woocommerce_checkout_create_order_line_item', 'checkout_create_order_line_item', 10, 4
Thanks
Hi Christophe,
Thank you for contacting us and I'd be happy to assist.
If your goal is to get the value from the product's custom field and then save it as an additional line/metadata with the ordered item, the following forum thread has a useful example:
https://wordpress.stackexchange.com/a/329673
( screenshot: hidden link )
I hope this helps and for more accurate and up-to-date information related to WooCommerce's built-in hooks and filters, we'll recommend consulting its official support team and documentation.
regards,
Waqar
Hello,
Code like this :
add_action( 'woocommerce_checkout_create_order_line_item', 'custom_checkout_create_order_line_item', 20, 4 );
function custom_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
// Get a product custom field value
$custom_field_value = get_post_meta( $item->get_product_id(), 'wpcf-numero-disque', true );
// Update order item meta
if ( ! empty( $custom_field_value ) ){
$item->update_meta_data( 'wpcf-numero-disque', $custom_field_value );
}
// … … Or … …
// Get cart item custom data and update order item meta
if( isset( $values['custom_data'] ) ) {
$item->update_meta_data( 'wpcf-numero-disque', $values['custom_data'] );
}
}
Thanks
Hi Christophe,
Thanks for writing back.
You don't need the complete code snippet and here is the shortened version:
add_action( 'woocommerce_checkout_create_order_line_item', 'custom_checkout_create_order_line_item', 20, 4 );
function custom_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
// Get a product custom field value
$custom_field_value = get_post_meta( $item->get_product_id(), 'wpcf-numero-disque', true );
// Update order item meta
if ( ! empty( $custom_field_value ) ){
$item->update_meta_data( 'Disque', $custom_field_value );
}
}
For more personalized assistance around custom code, you can also consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/
regards,
Waqar