WordPress at Your Fingertips
function is not described

WC_Product_Data_Store_CPT::update_product_sales() public WC 3.0.0

Update a product's sale count directly.

Uses queries rather than update_post_meta so we can do this in one query for performance.

{} It's a method of the class: WC_Product_Data_Store_CPT{}

Hooks from the method

Return

null. Nothing.

Usage

$WC_Product_Data_Store_CPT = new WC_Product_Data_Store_CPT();
$WC_Product_Data_Store_CPT->update_product_sales( $product_id, $quantity, $operation );
$product_id(int) (required)
Product ID.
$quantity(int|null)
Quantity.
Default: null
$operation(string)
set, increase and decrease.
Default: 'set'

Changelog

Since 3.0.0 Introduced.
Since 3.0.0 this supports set, increase and decrease.

Code of WC_Product_Data_Store_CPT::update_product_sales() WC 5.8.0

public function update_product_sales( $product_id, $quantity = null, $operation = 'set' ) {
	global $wpdb;
	add_post_meta( $product_id, 'total_sales', 0, true );

	// Update stock in DB directly.
	switch ( $operation ) {
		case 'increase':
			// phpcs:ignore WordPress.VIP.DirectDatabaseQuery.DirectQuery
			$wpdb->query(
				$wpdb->prepare(
					"UPDATE {$wpdb->postmeta} SET meta_value = meta_value + %f WHERE post_id = %d AND meta_key='total_sales'",
					$quantity,
					$product_id
				)
			);
			break;
		case 'decrease':
			// phpcs:ignore WordPress.VIP.DirectDatabaseQuery.DirectQuery
			$wpdb->query(
				$wpdb->prepare(
					"UPDATE {$wpdb->postmeta} SET meta_value = meta_value - %f WHERE post_id = %d AND meta_key='total_sales'",
					$quantity,
					$product_id
				)
			);
			break;
		default:
			// phpcs:ignore WordPress.VIP.DirectDatabaseQuery.DirectQuery
			$wpdb->query(
				$wpdb->prepare(
					"UPDATE {$wpdb->postmeta} SET meta_value = %f WHERE post_id = %d AND meta_key='total_sales'",
					$quantity,
					$product_id
				)
			);
			break;
	}

	wp_cache_delete( $product_id, 'post_meta' );

	$this->update_lookup_table( $product_id, 'wc_product_meta_lookup' );

	/**
	 * Fire an action for this direct update so it can be detected by other code.
	 *
	 * @since 3.6
	 * @param int $product_id Product ID that was updated directly.
	 */
	do_action( 'woocommerce_updated_product_sales', $product_id );
}