WC_Product_Data_Store_CPT::update_product_sales()
Update a product's sale count directly.
Uses queries rather than update_post_meta so we can do this in one query for performance.
Method of the class: WC_Product_Data_Store_CPT{}
Hooks from the method
Return
null
. Nothing (null).
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. |
WC_Product_Data_Store_CPT::update_product_sales() WC Product Data Store CPT::update product sales code WC 9.3.3
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 ); }