I have a problem with adding action to 'save_post_product' hook. I want to send stock data to my external API when product is changed(updated) in woocommerce admin.
The problem is that the stock values i get from simple product after the action is called are one 'iteration' old. By that i mean that the stock data i get seem to be the data before update. so if i call the update product 2 times, first time i get old data, second time i get the new ones.
add_action('save_post_product', array($this, 'product_changed'), 99, 3);
function product_changed($post_id, $post, $update)
    {
        if ('product' != $post->post_type || $update != true) {
            return;
        }
        $_pf = new WC_Product_Factory();
        $product = $_pf->get_product($post_id);
        $items = array();
        if ($product->product_type == 'simple') {
            $product->get_total_stock();
            $inStock = $product->is_in_stock();
            $qty = $product->get_stock_quantity();
            $managing = $product->managing_stock();
            $items[$product->id] = [
                ...
            ];
        } elseif ($product->product_type == 'variable') {
            $variations = $product->get_available_variations();
            /*For variations it works properly*/
            }
        }
        $itemsJson = json_encode($items);
        $this->sendData($itemsJson, '/products-changed/');    
    }
TLDR (example):
Lets say that product is set to manage stock, stock quantity 500 and is in stock.
Now i change the product not to manage stock, and set that it is out of stock. I hit update. Everything runs and wordpress gets to my code. When i get the values i still get
$product->is_in_stock(); //true
$product->get_stock_quantity(); //500
$product->managing_stock(); //yes
Now, when i hit the update again, everything runs the second time, but now i get the correct values.
$product->is_in_stock(); //false
$product->get_stock_quantity(); //0
$product->managing_stock(); //no
I assume that the product stock update runs after 'save_post_product' hook however, i was not able to find any other hook that might solve my problem.
NOTE: It works well with variations in the first 'iteration'. I think it has to do something with the $product->get_available_variations() code.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire