I have a custom order status called 'cancel-by-admin' which is set when an order is cancelled by site admin for some reason.
Now we need to increase/adjust the produce stock count when the order is cancelled. WooCommerce has already provided 'cancel' order status and when it is set the stock count get adjusted by existing code. We need to implement the same functionality for 'cancel-by-admin' status.
How to achieve that? I am using Woocommerce 6.3.1.
Someone suggested to use the function wc_update_product_stock()
. Also this link: https://stackoverflow.com/a/51940564/696680
But I am note sure what would be the best approach. Note that a customer can order multiple products in a single order, hence when the admin cancel the order, all the associated product quantity need to be adjusted.
To add the custom order status I use the following code:
add_action( 'init', 'register_custom_order_statuses', 20 );
function register_custom_order_statuses() {
register_post_status( 'wc-cancelled-by-us', array(
'label' => _x( 'CancelledByAdmin', 'Order status', 'woocommerce' ),
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'CancelledByAdmin <span class="count">(%s)</span>', 'CancelledByAdmin <span class="count">(%s)</span>', 'woocommerce' )
) );
}
And my code attempt, where I could use some advice on how to proceed:
add_action('woocommerce_order_status_changed', 'func_status_changed', 10, 4 );
function func_status_changed( $order_id, $old_status, $new_status, $order ){
if ( $new_status == 'cancelled-by-us' ) {
// Stock update operation goes here
}
}