wc_update_product_stock

Update a product's stock amount.

Description

wc_update_product_stock( (int|WC_Product) $product, (constant) $stock_quantity = null, (string) $operation = 'set' ); 

Uses queries rather than update_post_meta so we can do this in one query (to avoid stock issues).

Parameters (3)

0. $product (int|WC_Product)
The product.
1. $stock_quantity — Optional. (constant) => null
The stock quantity.
2. $operation — Optional. (string) => 'set'
Set, increase and decrease.

Usage

  1. if ( !function_exists( 'wc_update_product_stock' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'woocommerce/includes/wc-stock-functions.php'; 
  3.  
  4. // The product. 
  5. $product = null; 
  6.  
  7. // The stock quantity. 
  8. $stock_quantity = null; 
  9.  
  10. // set, increase and decrease. 
  11. $operation = 'set'; 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = wc_update_product_stock($product, $stock_quantity, $operation); 
  15.  

Defined (1)

The function is defined in the following location(s).

/includes/wc-stock-functions.php  
  1. function wc_update_product_stock( $product, $stock_quantity = null, $operation = 'set' ) { 
  2. if ( ! $product = wc_get_product( $product ) ) { 
  3. return false; 
  4. if ( ! is_null( $stock_quantity ) && $product->managing_stock() ) { 
  5. // Some products (variations) can have their stock managed by their parent. Get the correct ID to reduce here. 
  6. $product_id_with_stock = $product->get_stock_managed_by_id(); 
  7. $data_store = WC_Data_Store::load( 'product' ); 
  8. $data_store->update_product_stock( $product_id_with_stock, $stock_quantity, $operation ); 
  9. delete_transient( 'wc_low_stock_count' ); 
  10. delete_transient( 'wc_outofstock_count' ); 
  11. delete_transient( 'wc_product_children_' . ( $product->is_type( 'variation' ) ? $product->get_parent_id() : $product->get_id() ) ); 
  12. wp_cache_delete( 'product-' . $product_id_with_stock, 'products' ); 
  13.  
  14. // Re-read product data after updating stock, then have stock status calculated and saved. 
  15. $product_with_stock = wc_get_product( $product_id_with_stock ); 
  16. $product_with_stock->set_stock_status(); 
  17. $product_with_stock->save(); 
  18.  
  19. do_action( $product_with_stock->is_type( 'variation' ) ? 'woocommerce_variation_set_stock' : 'woocommerce_product_set_stock', $product_with_stock ); 
  20.  
  21. return $product_with_stock->get_stock_quantity(); 
  22. return $product->get_stock_quantity();