In functions.php
add_action( 'woocommerce_add_order_item_meta', 'custom_add_item_sku', 10, 3 );
function custom_add_item_sku( $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 );
}
But its showing SKU value below Product title but i want it like this
SKU:123sd - Product Name
Update 2018-04-01 - Changing of hook and Improved code.
Use woocommerce_order_item_name filter hook instead. I have make some changes in your code:
add_filter( 'woocommerce_order_item_name', 'sku_before_order_item_name', 30, 3 );
function sku_before_order_item_name( $item_name, $item, $is_visible ) {
$product = $item->get_product();
$sku = $product->get_sku();
// When sku doesn't exist we exit
if( empty( $sku ) ) return $item_name;
$sku_text = __( 'SKU', 'woocommerce' ) . ': ' . $sku;
// Add product permalink when argument $is_visible is true
$product_permalink = $is_visible ? $product->get_permalink( $item ) : '';
if( $product_permalink )
return sprintf( '<a href="%s">%s - %s</a>', $product_permalink, $sku_text, $item->get_name() );
else
return $sku_text . ' - ' . $item->get_name();
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested in WooCommerce 3+ and works.
Displaying the SKU in cart items name (Updated: with the link for cart page):
add_filter( 'woocommerce_cart_item_name', 'sku_before_cart_item_name', 10, 3 );
function sku_before_cart_item_name( $product_name, $cart_item, $cart_item_key ) {
$product = $cart_item['data'];
$sku = $product->get_sku();
// When sku doesn't exist we exit
if( empty( $sku ) ) return $product_name;
$sku_text = __( 'SKU', 'woocommerce' ) . ': ' . $sku;
$product_permalink = $product->get_permalink( $cart_item );
if ( is_cart() )
return sprintf( '<a href="%s">%s - %s</a>', esc_url( $product_permalink ), $sku_text, $product->get_name() );
else
return $sku_text . ' - ' . $product_name;
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested in WooCommerce 3+ and works.
I would change the hook to 'woocommerce_new_order_item' as it seems like there may be some deprecation issues with the 'woocommerce_add_order_item_meta'
Something like this should add the name after the SKU, but I don't know if that's exactly what you're looking for.
add_action( 'woocommerce_new_order_item', 'custom_add_item_sku', 10, 3 );
function custom_add_item_sku( $item_id, $values, $cart_item_key ) {
$item_sku = get_post_meta( $values[ 'product_id' ], '_sku', true );
$name = = $values['name'];
wc_add_order_item_meta( $item_id, 'SKU', $item_sku . ' - ' . $name , false );
}