Im trying to add a line item when I update an order in the backend and it matches the status update of "enquiry" but no item is added.
I tried both get_status
and has_status
but I cant get it to work. Any ideas on why this isn’t working?
Code:
add_action( 'woocommerce_order_status_changed', 'add_free_products', 20, 4 );
function add_free_products( $order_id, $order ){
if ( ! $order_id )
return;
// Getting an instance of the order object
$order = wc_get_order( $order_id );
if( $order->get_status() == 'enquiry' ) {
$product_id = '155185';
$product = wc_get_product( $product_id );
$order->add_product( $product);
$order->save();
}
}
2
Answers
For a custom order status you could use the
woocommerce_order_status_' . $status_transition['to']
action hook, where you will replace$status_transition[to]
byenquiry
So you get:
There are some mistakes and missing things, Use the following instead:
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Addition 1
You could also flag this action with custom meta data, to avoid adding multiple products if you change order status multiple times with the following:
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Addition 2 – Check if the product has been already added to the order (avoiding adding the product multiple times):
Code goes in functions.php file of the active child theme (or active theme). Tested and works.