How to change a WooCommerce Subscription Deposit and Monthly Payment?

A customer wants some specific/bespoke discounts to the subscription service they sell. I cannot find a plugin to do what they want, so thought I would code it myself.

But I cannot find how to edit the initial payment item in the cart for subscriptions.

Using woocommerce_before_calculate_totals I can edit the monthly amount. But the initial payment does not change. Even though it is looping its price below because I can output it to the screen, so I think $cart_item['data']->set_price( $new_price ) is not changing the price of the initial payment.

I can change it via woocommerce_cart_subtotal, but I cant see how to get the original price in that function to make the adjustment. But then that does not go on to change tax and total anyway.

For info, the code below does not use $cart_item['data']->get_price() because woocommerce_before_calculate_totals seems to be called twice which spoils my calculations.

function set_new_customer_discount( $cart )
{
    // Loop Through cart items
    foreach ( $cart-get_cart() as $key = $cart_item )
    {
        //Hook seems to be firing twice for some reason... Get the price from the original product data, not from the cart...
        $item_id = $cart_item['data']-id;
        $product = wc_get_product( $item_id );
        $original_price = $product-get_price();
        $new_price = $original_price/2;
        $cart_item['data']-set_price( $new_price );
    }
}
add_action('woocommerce_before_calculate_totals', 'set_new_customer_discount', 20, 1 );

The basket looks like this and I am trying to take for example 10% off both the "To pay now" lines and the "Recurring Totals" lines:

Basket totals

To pay now

Subtotal    £400.00
VAT £80.00
Total   £480.00

Recurring Totals

Subtotal    £577.80 / month for 5 months
VAT £115.56 / month for 5 months
Recurring Total £693.36 / month for 5 months
First payment: 9th May 2019

Topic woocommerce-offtopic subscription hooks Wordpress

Category Web


I THINK I have achieved what I want in this far more simple fee hook, found here https://stackoverflow.com/questions/43415783/change-cart-total-price-in-woocommerce:

function prefix_add_discount_line( $cart )
{
    $discount = $cart->subtotal_ex_tax * 0.1;
    $cart->add_fee( __( '10% Discount', 'yourtext-domain' ) , -$discount );
}
add_action( 'woocommerce_cart_calculate_fees', 'prefix_add_discount_line' );

This is taking 10% off the "To pay now" including tax and totals, and then 10% off "Recurring Totals" including tax and totals.

Note: Notice I am using $cart->subtotal_ex_tax and not $cart->subtotal, because $cart->subtotal is returning the subtotal plus tax, even though the cart table shows "subtotal" as the price ex. tax.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.