Skip to content

Instantly share code, notes, and snippets.

@MCKLtech
Created March 7, 2019 20:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MCKLtech/9127918e5488a21c8115a0eab14533bb to your computer and use it in GitHub Desktop.
Save MCKLtech/9127918e5488a21c8115a0eab14533bb to your computer and use it in GitHub Desktop.
HOWTO: Adding A Discount or Fee to a WooCommerce Order Programmatically
<?php
/*
* The following code assumes you have an WC Order object already. We'll be adding a discount to an order.
* This code cannot be added directly anywhere, it is merely an explanation of how this can be done.
* We will add a discount to the order using Fees
*/
/* Assume order is set up already */
//Always save an order first.
$order->save();
//Set up the Item Fee
$fee = new WC_Order_Item_Fee();
//Give the Fee a name e.g. Discount
$fee->set_name('Discount');
//I'll be adding a 50 discount, hence multiply by negative one.
$total_fee = 50 * -1;
//Set the Fee
$fee->set_total($total_fee);
//Add to the Order
$order->add_item($fee);
//Recalculate the totals. IMPORTANT!
$order->calculate_totals();
//Save the Order
$order->save();
//We'll complete the order here, but it doesn't have to be.
$order->update_status("completed");
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment