WC_Product_Data_Store_CPT::set_product_stock( int $product_id_with_stock, int|float|null $stock_quantity )

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


Description Description

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


Parameters Parameters

$product_id_with_stock

(Required) Product ID.

$stock_quantity

(Required) Stock quantity.


Top ↑

Source Source

File: includes/data-stores/class-wc-product-data-store-cpt.php

	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' );
	}

Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.