How to Sync Product Stock Programmatically
There are two ways to run the stock sync for a specific WooCommerce product in your code.
First of all, I want to highlight that triggering the hooks woocommerce_product_set_stock and woocommerce_variation_set_stock won’t do the trick – my plugin doesn’t use them because these hooks are very slow when you need to sync a lot of products within a single order.
The first method is to run the save_post or (better) save_post_product hook:
// trigger the stock sync
do_action( 'save_post_product', $post_id, $post );When you use this method for a variable product, all its variations are going to be synced. However, you can not run it for a specific product variation.
- $post_idint
- The product ID.
- $postWP_Post
- The post object of a product. You can use the
get_post()function to get it.
Another way is to trigger the sync using the product_sync() static method of the Rudr_Simple_Product_Sync class.
// trigger the stock sync
Rudr_Simple_Product_Sync::product_sync( $product );This method can be used for both products and variations.
- $productmixed
- The product
WC_Productobject or product variationWC_Product_Variationobject. You can get it with thewc_get_product()WooCommerce function, for example.
Both methods will trigger the inventory sync to all connected stores.