wc_update_product_stock( int|WC_Product $product, int|null $stock_quantity = null, string $operation = 'set', bool $updating = false )
Update a product’s stock amount.
Description Description
Uses queries rather than update_post_meta so we can do this in one query (to avoid stock issues).
Parameters Parameters
- $product
-
(Required) Product ID or product instance.
- $stock_quantity
-
(Optional) Stock quantity.
Default value: null
- $operation
-
(Optional) Type of opertion, allows 'set', 'increase' and 'decrease'.
Default value: 'set'
- $updating
-
(Optional) If true, the product object won't be saved here as it will be updated later.
Default value: false
Return Return
(bool|int|null)
Source Source
File: includes/wc-stock-functions.php
function wc_update_product_stock( $product, $stock_quantity = null, $operation = 'set', $updating = false ) {
if ( ! is_a( $product, 'WC_Product' ) ) {
$product = wc_get_product( $product );
}
if ( ! $product ) {
return false;
}
if ( ! is_null( $stock_quantity ) && $product->managing_stock() ) {
// Some products (variations) can have their stock managed by their parent. Get the correct object to be updated here.
$product_id_with_stock = $product->get_stock_managed_by_id();
$product_with_stock = $product_id_with_stock !== $product->get_id() ? wc_get_product( $product_id_with_stock ) : $product;
$data_store = WC_Data_Store::load( 'product' );
// Update the database.
$new_stock = $data_store->update_product_stock( $product_id_with_stock, $stock_quantity, $operation );
// Update the product object.
$data_store->read_stock_quantity( $product_with_stock, $new_stock );
// If this is not being called during an update routine, save the product so stock status etc is in sync, and caches are cleared.
if ( ! $updating ) {
$product_with_stock->set_stock_status();
$product_with_stock->save();
}
// Fire actions to let 3rd parties know the stock changed.
if ( $product_with_stock->is_type( 'variation' ) ) {
do_action( 'woocommerce_variation_set_stock', $product_with_stock );
} else {
do_action( 'woocommerce_product_set_stock', $product_with_stock );
}
return $product_with_stock->get_stock_quantity();
}
return $product->get_stock_quantity();
}
Changelog Changelog
| Version | Description |
|---|---|
| 3.0.0 | Introduced. |