'Subtotal price on WooCommerce Cart

The below function calculates a price based on quantity, an attribute value and the base price set on the variation.

While I can update the base price, how can I update the line subtotal without affecting the base price?

I was hoping for something logical like $cart_item['data']->set_subtotal($total); in place of $cart_item['data']->set_price($total); but there doesn't appear to be anything from research.

add_action('woocommerce_calculate_totals','my_woocommerce_calculate_totals');

function my_woocommerce_calculate_totals($cart) {

    // Loop over $cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {

        // Get line specific data
        $roll_width = (float)$cart_item['variation']['attribute_pa_roll-width'];
        $line_subtotal = (float)$cart_item['line_subtotal'];
        $line_total = $line_subtotal * $roll_width;
        $total = number_format((float)$line_total, 2, '.', '');

        // Set price
        $cart_item['data']->set_price($total);
    
    }
  
}


Solution 1:[1]

This can be done using the following function, but please post if there is a better way to achieve this:

function my_woocommerce_cart_product_subtotal( $product_subtotal, $product, $quantity, $instance ) { 

    // Get line specific data
    $roll_width = (float)$product->attributes['pa_roll-width'];
    $line_total = (float)$product->get_price() * $roll_width * $quantity;
    $product_subtotal = number_format((float)$line_total, 2, '.', '');

    return wc_price($product_subtotal); 

};

add_filter( 'woocommerce_cart_product_subtotal', 'my_woocommerce_cart_product_subtotal', 10, 4 ); 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user1235285