As an organization (whether for profit or not for profit) you are trying to accomplish…
February 2022: This code may be out of date. We’re not currently scheduled to release any updates or fixes for this and cannot validate that it still works with current versions of WooCommerce.
Request
This question came from Stack Overflow asking, for warranty purposes, how to save a product’s SKU to the order item meta for future discovery.
The problem is that when a product still exists in an installation the SKU is available for reporting, etc. But once that product is deleted the SKU reference is now gone. Saving it to the order item meta is a good idea.
Required Plugins
Code
add_action( 'woocommerce_add_order_item_meta', 'majemedia_save_item_sku_order_itemmeta', 10, 3 ); function majemedia_save_item_sku_order_itemmeta( $item_id, $values, $cart_item_key ) { $item_sku = get_post_meta( $values[ 'product_id' ], '_sku', true ); wc_add_order_item_meta( $item_id, 'sku', $item_sku , false ); }
Result
Going Further
The above will work only in cases where a product has been added to the cart that doesn’t have any variations. The following will not only save the parent SKU but also the variation SKU to the item meta.
add_action( 'woocommerce_add_order_item_meta', 'majemedia_save_item_sku_order_itemmeta', 10, 3 ); function majemedia_save_item_sku_order_itemmeta( $item_id, $values, $cart_item_key ) { $item_sku = get_post_meta( $values[ 'product_id' ], '_sku', true ); $item_has_variation = ( ! empty( $values[ 'variation_id' ] ) ? true : false ); if( $item_has_variation ) { wc_add_order_item_meta( $item_id, 'parent_sku', $item_sku, false ); $variation_sku = get_post_meta( $values[ 'variation_id' ], '_sku', true ); wc_add_order_item_meta( $item_id, 'variation_sku', $variation_sku, false ); } else { wc_add_order_item_meta( $item_id, 'sku', $item_sku , false ); } }
Result
Disclaimer
Purrly Digital LLC cannot be held responsible for the functionality of this code. Please make sure you test it on a development site before adding the code to your production website. There is no support available for this (and other) code snippet(s) posted on this website. If you’d like Purrly Digital to do custom development to help with your custom implementation please send a contact request.
As of 3.0.1, the woocommerce_add_order_item_meta hook has been deprecated and the new hook is woocommerce_new_order_item($item_id, $item, $order_id)
Pascal,
Thanks for that info. I’ll have to schedule this post for an update.
Hi there,
Any chance you could update this with the new hook 🙂
I am using https://automatewoo.com/ to push Order Meta to a contact in Active Campaign.
I’d like to get the SKU of all items in the order, and add them to a custom meta field with all the SKUs separated with commas.
When https://automatewoo.com/ pushes this field of sku’s separated by commas, it breaks each comma value into it’s own tag for the contact.
Hi,
Is this code works for composite products?