Stock Management is a default feature on all Online Store CMS, it’s useful when you manage your stock using WooCommerce, preventing out-of-stock Purchases and of course, preventing your clients’ complaints.
Sometimes, beyond this obvious feature, we need to know some more about the stock status. For example: occasionally, for business rules’ reasons, it could be useful if we could know the stock status of the product at the date of a specific order.
It would be useful if your Online Store provides the Stock Status of each product at the date/time of the Order. Let’s do it, step by step:
1) Save the Stock Status at the Order Moment
This info isn’t stored by default, so my suggestion is saving the stock info as a Custom Post Metadata. And the ideal moment to store this info is after the checkout confirmation.
function samuelsilva_save_stock_items( $order_id ){
// Get the order object
$order = new WC_Order( $order_id );
// Get the items
$items = $order->get_items();
// The array that will be filled with the stock
$stock_array = array();
// Items loop
foreach ( $items as $item ) {
$product = wc_get_product( $item['product_id'] );
// Get the stock
$stock_status = $product->get_stock_status();
$stock_array[$product_id] = $stock_status;
}
// After the loop, save our Associative (ID) Array of stocks
update_post_meta( $order_id, 'stock_at_the_time', $stock_array );
}
// This function will run after the WooCommerce Checkout
add_action( 'woocommerce_checkout_order_processed', 'samuelsilva_save_stock_items', 10, 2 );
Well, now each completed Order we have the Products’ Stock statuses of that specific time.
2) Show the Stock Status (at the Order moment)
The next step is to decide where we should show this new useful information. There are a lot of places where we can show this information: Admin Emails, Admin Order Page, Orders’ History (for the User), etc… In my specific case, my needs were met with just the information on the Admin Orders’ Panel.
Before this new column on the Admin Order’s table, let’s develop a quick and clean way to access our new stock info:
function get_stock_at_the_time( $order_id = false, $product_id = false ){
if( ! $order_id || ! $product_id ){
return false;
}
$stock = get_post_meta( $order_id, 'stock_at_the_time' )[0];
if( $stock ){
return $stock[$product_id];
}
}
Now, we just need to use this function for getting the Product’s stock at the time of that specific order. The final result, in my situation, was this:
Let me know in the comments if you need additional suggestions for displaying this new info.
Leave a Reply