You can use the woocommerce_update_product_stock_query hook found inside the update_product_stock and set_product_stock methods of the WC_Product_Data_Store_CPT class.
This hook is activated before the product stock quantity update query
is executed. Through it you will have access to the previous and new
product stock quantity (regardless of the type of operation).
Then you can use the $product object to get the old stock quantity of the product (since the product is not yet updated), via $product->get_stock_quantity().
The possible operations are: set, increase or decrease.
// get old and new product stock quantity
add_filter( 'woocommerce_update_product_stock_query', 'get_old_and_new_product_quantity_stock', 10, 4 );
function get_old_and_new_product_quantity_stock( $sql, $product_id_with_stock, $new_stock, $operation ) {
$product = wc_get_product( $product_id_with_stock );
$old_stock_quantity = $product->get_stock_quantity();
$new_stock_quantity = $new_stock;
// run your code
return $sql;
}
To save the previous product stock quantity as a custom post meta you can use the following function:
// save the previous product stock quantity
add_filter( 'woocommerce_update_product_stock_query', 'get_old_and_new_product_quantity_stock', 10, 4 );
function get_old_and_new_product_quantity_stock( $sql, $product_id_with_stock, $new_stock, $operation ) {
$product = wc_get_product( $product_id_with_stock );
// save the previous product stock quantity as a custom post meta "_old_stock_quantity"
update_post_meta( $product_id_with_stock, '_old_stock_quantity', $product->get_stock_quantity() );
// updates the product stock quantity
return $sql;
}
The code has been tested and works. Add it to your active theme's functions.php.
FOR INFORMATION
If the operation was decrease and the quantity was 2, the value of the $sql variable would be:
UPDATE wp_postmeta SET meta_value = meta_value -2.000000 WHERE post_id = 14 AND meta_key='_stock'