HOWTO: Adding A Discount or Fee to a WooCommerce Order Programmatically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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