Search code examples
phpwoocommercehook-woocommerceordersdiscount

Add the discount total for each item as WooCommerce order item metadata


I need to add in order metadata the amount of the discount for each product individually. For example, There are ten products in the order. The user has applied a coupon discount to the products. The total amount of the discount was calculated (if there are products on_sale, they were not taken into discount calculate).

But in the end, we got a total discount. And I need to split this discount for all the products that received it and even write this value into order item metadata.

Why don't I even have a sample code? I just don't know where to start. The only thing I think is to take the total discount, divide it by the number of products that can have a discount (these are all products in the order except on_sale), And add the resulting number to the product meta. But there is a problem, I'm not sure if this is the right solution. Could you please share any advice on how to solve this?


Solution

  • You can start with woocommerce_checkout_create_order_line_item action hook where you will be able to set custom order item meta data. This hook has 4 arguments:

    • $item the order item (object),
    • $cart_item_key the cart item key (string),
    • $values the cart item (array),
    • $order the order (object).

    So you can get from the cart item $values the discounted line item totals using:

    $line_discount     = $value['line_subtotal'] - $value['line_total'];
    $line_discount_tax = $value['line_subtotal_tax'] - $value['line_tax'];
    

    Then for example all together to save the line discount total as custom order item meta data:

    // Save Line item discount as custom order item meta data
    add_action('woocommerce_checkout_create_order_line_item', 'action_checkout_create_order_line_item', 10, 4 );
    function action_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
        $line_discount     = $value['line_subtotal'] - $value['line_total'];
        $line_discount_tax = $value['line_subtotal_tax'] - $value['line_tax'];
        
        $item->update_meta_data( '_line_discount', $line_discount + $line_discount_tax );
    }
    

    Code goes in functions.php file of the active child theme (or active theme). Tested and works.

    Then you can get it from an order item object $item using the WC_Data method get_meta() like:

     $line_discount = $item->get_meta('_line_discount');
    

    Related: Get Order items and WC_Order_Item_Product in WooCommerce 3