Get a reason for change in stock when using the woocommerce_product_set_stock hook

Viewed 545

I am using woocommerce and have created a custom table in order to monitor stock movements on products. I am using the woocommerce_product_set_stock hook in order to achieve this and it is working successfully. This shows the amount by which stock level is increased or decreased and by which user, date etc. Here is the function:

 add_action( 'woocommerce_product_set_stock', array( $this, 'save_stock' ) );
    
 public function save_stock( $product ) {
    //get the previous stock level from the custom table
    global $wpdb;
    $old_qty = $wpdb->get_var("SELECT qty FROM wp_stock_log WHERE product_id = '".$product->get_id()."' ORDER BY id DESC LIMIT 1 ");
    
    //get current stock level and calculate the change.
    $qty = $product->get_stock_quantity();
    $change_in_stock = $qty-$old_qty;
    
    //get user full name
    $current_user = wp_get_current_user();
    $first_name = $current_user->user_firstname;
    $last_name = $current_user->user_lastname;
    $full_name = $first_name . ' ' . $last_name;
    
    $data = array();
    //insert new row into the custom table
    $data['date_created'] = date( 'Y-m-d H:i:s', time() );
    $data['qty'] = $product->get_stock_quantity();
    $data['qty_change'] = $change_in_stock;
    $data['product_id'] = $product->get_id();
    $data['user'] = $full_name;
    $data['reason'] = SOME REASON ;
    $wpdb->insert( $wpdb->prefix.'stock_log', $data ); 
}

The wp_stock_log table is as follows:

|--------|--------------|------------|-----|----------|-----------|-------------|
|   ID   | date_created | product_id | qty |qty_change|   user    | reason      |
|--------|--------------|------------|-----|----------|-----------|-------------|
|   1    | 14-08-2020   | 123        | 12  |  -2      | Customer1 | Sale        |
|--------|--------------|------------|-----|----------|-----------|-------------|
|   2    | 15-08-2020   | 123        | 10  |  -1      | Customer2 | Sale        |
|--------|--------------|------------|-----|----------|-----------|-------------|
|   3    | 15-08-2020   | 123        |  9  |   4      | Manager   | Stock Added |
|--------|--------------|------------|-----|----------|-----------|-------------|
|   4    | 17-08-2020   | 123        |  13 |  -1      | Customer2 | Sale        |
|--------|--------------|------------|-----|----------|-----------|-------------|

I would like to show the reason for the change in stock, for example "Sale" if a customer has placed an order, or "Stock Added" if a shop manager has added new stock to inventory. How could I achieve this. Is there an existing property that I will be able to use to tell me if it is related to an order?

0 Answers
Related