Reputation: 6380
I'm trying to programmatically add an existing product to an order but change the name and price, just for this order.
I can add the existing product easily enough using:
$subscription->add_product( get_product( '969' ), 1);
How can I set a custom name and price for that?
If I can set that I then know I can run the following to recalculate the totals:
$subscription->calculate_totals();
Upvotes: 0
Views: 1346
Reputation: 253968
To change product price and name added to a subscription try the following:
$product = wc_get_product('969');
$quantity = 1;
$new_price = 100; // (Excluding taxes).
$new_name = 'New name';
// Add the product
$item_id = $subscription->add_product( $product, $quantity );
// Get the instance of WC_Order_Item_Product Object from item Id
$item = $subscription->get_item( $item_id, false ); // Get the
// Change name and price
$item->set_name( $new_name ); // set new name
$item->set_subtotal( $new_price * $item_quantity ); // set new price
// Calculate item taxes
$item->calculate_taxes( array(
'country' => $subscription->get_billing_country() ? $subscription->get_billing_country() : $subscription->get_shipping_country(),
'state' => $subscription->get_billing_state() ? $subscription->get_billing_state() : $subscription->get_shipping_state(),
'postcode' => $subscription->get_billing_postcode() ? $subscription->get_billing_postcode() : $subscription->get_shipping_postcode(),
'city' => $subscription->get_billing_city() ? $subscription->get_billing_city() : $subscription->get_shipping_city(),
) );
$item->save(); // Save item
$subscription->calculate_totals(); // Refresh subscription totals and save.
It should work.
Related: Programmatically created WooCommerce order have no tax for new users
Upvotes: 1