Inventory Manager provides a PHP function to read and change product stock safely from your own code. Use it when you connect a barcode scanner, point of sale, warehouse or other external system to your catalog.
Where the stock is stored
The available quantity is stored in the _inventory product meta field as a whole number. An empty value means that the stock of this product is not managed (unlimited).
To read the current stock, use:
get_product_inventory( $product_id );Change the stock
ic_inventory_adjust_stock( $product_id, $delta, $args );- $product_id – the product ID.
- $delta – the change as a whole number, for example -1 for a sold item or 5 for received goods.
- $args – optional settings described below.
The function returns:
- the new stock quantity when the change is saved,
- false when the change is rejected (for example, not enough stock),
- null when the product’s stock is not managed. The stock is not changed in this case.
The change is saved in a single database operation, so two simultaneous sales cannot both take the last item and no change overwrites another one. Orders placed in the store use the same mechanism.
Example: sell one item in a physical store
$new_stock = ic_inventory_adjust_stock( $product_id, -1 );
if ( false === $new_stock ) {
// Not enough stock: the item is no longer available.
}Optional settings
- mode – strict (default) rejects a change that would make the stock negative. clamp takes as much as is available and stops at zero.
- context – an array with your own information, such as the source of the change. It is passed to the ic_inventory_changed action.
- variation_id and variation_index – identify a product variation (the variation field number and the position of the selected option) to change the variation stock instead of the main product stock. Both are required together.
- result – an object that receives the previous stock (old), the new stock (new) and the change that was really applied (applied_delta).
$result = new stdClass();
ic_inventory_adjust_stock(
$product_id,
-3,
array(
'mode' => 'clamp',
'context' => array( 'source' => 'pos' ),
'result' => $result,
)
);
// $result->applied_delta is -1 if only one item was available.React to stock changes
- ic_inventory_changed – runs after every saved change with the product ID, the new stock, the previous stock and the context.
- ic_inventory_empty – runs when the stock reaches zero.
- ic_inventory_added – runs when stock is added and the product is available again.
add_action( 'ic_inventory_changed', function ( $product_id, $new_stock, $old_stock, $context ) {
// For example, log the change or notify an external system.
}, 10, 4 );Order stock
Orders reduce and return stock automatically, as described in Automatic Inventory Management. You do not need to call the function for store orders.
This function is available in Inventory Manager 1.7.0 and newer.
