In Woocommerce, I am adding products to cart using the GET method from an URL like:
http://example.com/cart/?add-to-cart=10
Now I would like to be able adding at the same time some custom data as a product note like:
http://example.com/cart/?add-to-cart=10¬e=hinote
And then saving that "hinote" value as the cart item data. Once oder is placed, I would like to save that "hinote" in order item data and display it as custom order item data everywhere.
Is that possible?
Any help is appreciated.
Yes that is possible and quiet simple… Try the following code:
// Add custom note as custom cart item data
add_filter( 'woocommerce_add_cart_item_data', 'get_custom_product_note', 30, 2 );
function get_custom_product_note( $cart_item_data, $product_id ){
if ( isset($_GET['note']) && ! empty($_GET['note']) ) {
$cart_item_data['custom_note'] = sanitize_text_field( $_GET['note'] );
$cart_item_data['unique_key'] = md5( microtime().rand() );
}
return $cart_item_data;
}
// Display note in cart and checkout pages as cart item data - Optional
add_filter( 'woocommerce_get_item_data', 'display_custom_item_data', 10, 2 );
function display_custom_item_data( $cart_item_data, $cart_item ) {
if ( isset( $cart_item['custom_note'] ) ){
$cart_item_data[] = array(
'name' => "Note",
'value' => $cart_item['custom_note'],
);
}
return $cart_item_data;
}
// Save and display product note in orders and email notifications (everywhere)
add_action( 'woocommerce_checkout_create_order_line_item', 'add_custom_note_order_item_meta', 20, 4 );
function add_custom_note_order_item_meta( $item, $cart_item_key, $values, $order ) {
if ( isset( $values['custom_note'] ) ){
$item->update_meta_data( 'Note', $values['custom_note'] );
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.