Skip to content
Advertisement

WooCommerce changing order line totals

I have a plugin which applies discounts based on the category of the product. I’m using the filters below to add text to the order table in the cart:

add_filter('woocommerce_cart_product_subtotal', array($this,'change_product_subtotal'), 10, 4);
add_filter( 'woocommerce_cart_product_price', array($this,'change_product_price'), 10, 2);
add_filter( 'woocommerce_cart_item_name', array($this,'change_product_name'), 10, 2);

And this action to change the total price of the order/cart.

add_action( 'woocommerce_after_calculate_totals', array($this,'ca_change_cart_total'), 10, 1 );

The total price of the order pulls through to the checkout, as do the modified product fields. However when the order has been placed, the filters no longer have any effect (however the total order price is correct). My question is: what are the hooks I need to use to add the text present in the cart, to the placed order screen OR what is an alternative approach that will achieve the same outcome.I have provided screenshots showing the stages of the order. Thanks for any contributions.Cart PageCheckout PageOrder Page

Advertisement

Answer

For anyone having the same issue. I found an alternative method to using filters. Upon order creation loop through all the items in the order and change the totals. This has the advantage of effectively changing the unit price of the each product so in the WooCommerce admin area, if you are needing to issue a refund, the correct unit price is displayed. I have shown my code below, obviously replace 999 with the relevant total price for each product (ie unit price * quantity) using whatever custom logic your use case requires.

add_action('woocommerce_checkout_create_order', 'on_checkout_create_order', 20, 2);
function on_checkout_create_order( $order, $data ) {
    foreach( $order->get_items() as $item_id => $line_item ){
        $order->items[$item_id]->set_subtotal(999);
        $order->items[$item_id]->set_total(999);
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement