1

I'm trying to create a custom meta_key in woocommerce_order_itemmeta table for (unit price excluding tax) to use later.

I added the below code but I keep getting an error on the checkout page, showing only the red mark with 'Internal Server Error'.

Someone who knows where things are going wrong?

// Save custom data to order item meta data

add_action( 'woocommerce_add_order_item_meta', 'unit_price_order_itemmeta', 10, 3 );
function unit_price_order_itemmeta( $item_id, $values, $cart_item_key ) {

        $unit_price  =  wc_get_price_excluding_tax( $product );

        wc_add_order_item_meta( $item_id, '_unit_price', $unit_price , false );

}
7uc1f3r
  • 28,449
  • 17
  • 32
  • 50
Bassam Radi
  • 169
  • 9

1 Answers1

1

In your code you use $product while this is not specified anywhere.

Note: woocommerce_add_order_item_meta hook is deprecated since WooCommerce 3. Use woocommerce_checkout_create_order_line_item instead

So replace:

// Save custom data to order item meta data
add_action( 'woocommerce_add_order_item_meta', 'unit_price_order_itemmeta', 10, 3 );
function unit_price_order_itemmeta( $item_id, $values, $cart_item_key ) {

    $unit_price  =  wc_get_price_excluding_tax( $product );

    wc_add_order_item_meta( $item_id, '_unit_price', $unit_price , false );

}

With

function action_woocommerce_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
    // The WC_Product instance Object
    $product = $item->get_product();
    
    $unit_price = wc_get_price_excluding_tax( $product );
        
    $item->update_meta_data( '_unit_price', $unit_price );
}
add_action('woocommerce_checkout_create_order_line_item', 'action_woocommerce_checkout_create_order_line_item', 10, 4 );
7uc1f3r
  • 28,449
  • 17
  • 32
  • 50
  • Its working great but the unit price shows as 15.658174. Is there a way to make in 15.66. – Bassam Radi Oct 14 '20 at 12:10
  • Before you assign `$unit_price` to the `meta_data` you can use a rounding function, see [Show a number to two decimal places](https://stackoverflow.com/questions/4483540/show-a-number-to-two-decimal-places). Regards – 7uc1f3r Oct 14 '20 at 13:27
  • 1
    I add this // $unit_price_value = number_format( $unit_price , 2 ); // and changed last line to $unit_price_value and its working – Bassam Radi Oct 14 '20 at 13:35