How to save previous product stock quantity in woocommerce?

Member

by jasen , in category: PHP CMS , 6 months ago

How to save previous product stock quantity in woocommerce?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 6 months ago

@jasen 

To save the previous product stock quantity in WooCommerce, you can create a custom plugin or add some custom code to your theme's functions.php file. Here is one way to do it using a custom plugin:

  1. Create a new plugin folder in your WordPress installation under wp-content/plugins/. For example, you can name it "custom-stock-history".
  2. Create a new PHP file inside this folder, e.g., custom-stock-history.php, and add the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?php
/*
Plugin Name: Custom Stock History
Description: Save previous product stock quantity in WooCommerce
Version: 1.0
*/

// Hook to save the previous stock quantity before it gets updated
add_action('woocommerce_before_product_object_save', 'save_previous_stock_quantity', 10, 2);
function save_previous_stock_quantity($product, $data_store) {
    $product_id = $product->get_id();
    $previous_quantity = get_post_meta($product_id, '_previous_stock_quantity', true);
    $current_quantity = $product->get_stock_quantity();

    // Save the previous stock quantity if it has changed
    if ($previous_quantity != $current_quantity) {
        update_post_meta($product_id, '_previous_stock_quantity', $previous_quantity);
    }
}


  1. Activate the plugin in the WordPress dashboard.


Now, whenever a product's stock quantity is updated in WooCommerce, the previous stock quantity will be saved as post meta with the key '_previous_stock_quantity'. You can then retrieve this value whenever needed to display or use it in your WooCommerce store.