Woocommerce: how to save products SKU in orders

Now the product SKU is related to the product, so when ordering and the product is not deleted it can be shown, but as soon as the product gets deleted the SKU is no longer available. Viewing orders can’t show the SKU anymore.

Related posts

Leave a Reply

2 comments

  1. Tested code

    use the woocommerce_add_order_item_meta hook. I’ve included two versions. 1 that only supports simple products. The second version supports variations as well.

    add_action( 'woocommerce_add_order_item_meta', 'so_28193771', 10, 3 );
    function so_28193771( $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 );
    
    }
    

    Product displayed on order receipt page

    Database view of 'sku' added to order item meta successfully

    Variation Support

    add_action( 'woocommerce_add_order_item_meta', 'so_28193771', 10, 3 );
    function so_28193771( $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 );
    
            }
    
    }
    

    Product displayed on order receipt page with variation
    Database view of 'sku' added to order item meta successfully with variation

  2. 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)