WC_Product_Data_Store_CPT::set_product_stock()protectedWC 1.0

Update a product's stock amount directly in the database.

Updates both post meta and lookup tables. Ignores manage stock setting on the product.

Method of the class: WC_Product_Data_Store_CPT{}

Return

null. Nothing (null).

Usage

// protected - for code of main (parent) or child class
$result = $this->set_product_stock( $product_id_with_stock, $stock_quantity );
$product_id_with_stock(int) (required)
Product ID.
$stock_quantity(int|float|null) (required)
Stock quantity.

WC_Product_Data_Store_CPT::set_product_stock() code WC 9.4.2

protected function set_product_stock( $product_id_with_stock, $stock_quantity ) {
	global $wpdb;

	// Generate SQL.
	$sql = $wpdb->prepare(
		"UPDATE {$wpdb->postmeta} SET meta_value = %f WHERE post_id = %d AND meta_key='_stock'",
		$stock_quantity,
		$product_id_with_stock
	);

	$sql = apply_filters( 'woocommerce_update_product_stock_query', $sql, $product_id_with_stock, $stock_quantity, 'set' );

	$wpdb->query( $sql ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.NotPrepared

	// Cache delete is required (not only) to set correct data for lookup table (which reads from cache).
	// Sometimes I wonder if it shouldn't be part of update_lookup_table.
	wp_cache_delete( $product_id_with_stock, 'post_meta' );

	$this->update_lookup_table( $product_id_with_stock, 'wc_product_meta_lookup' );
}