I am trying to allow users to update line items of their subscriptions from their my account panel. I am able to get their subscription from subscription id and show them update form. Right now I show them with product items in their subscription that I got through
$subscription = wcs_get_subscription($_GET['subscription']);
$subscription_items = $subscription->get_items();
What I am trying to do is allow users to update quantities of their product. So If they update quantity I want to update the subscription's item quantity so that future orders are generated with updated quantity.
I saw there is update_product method in WC_Abstract_Order
class. I think this can be used but I am confused on this note in comments:
* Update a line item for the order.
*
* Note this does not update order totals.
Do I need to recalculate totals when I use this? Also I needed to remove line item when quantity was 0. Is that possible?
As I do not see a remove item method.
Thanks
So I was able to make this work doing following.
note: I am using custom field price_level as it was dynamically priced during subscription and we wanted to use it so that price was same as when they subscribed.
//remove product items
$subscription->remove_order_items('line_item');
//add product item again
foreach($_POST['quantity'] as $product_id => $qty) {
if($qty > 0) {
//we will need to set dynamic prices based on cusotm field
$price_level = get_field('coffee_price_level', $subscription->id);
//Get the product
$product = wc_get_product($product_id);
//set the price
$product->set_price(floatval($price_level));
$tax = ($product->get_price_including_tax()-$product->get_price_excluding_tax())*$qty;
//subscription item price level
$subscription->add_product($product, $qty, array(
'totals' => array(
'subtotal' => $product->get_price(),
'subtotal_tax' => $tax,
'total' => $product->get_price(),
'tax' => $tax,
'tax_data' => array( 'subtotal' => array(1=>$tax), 'total' => array(1=>$tax) )
)
));
}
}