Merge pull request #13156 from woocommerce/fix-12802

Improve checkout performance when updating product sales
This commit is contained in:
Claudio Sanches 2017-02-11 13:53:32 -02:00 committed by GitHub
commit 633ed64b02
3 changed files with 46 additions and 4 deletions

View File

@ -981,6 +981,36 @@ class WC_Product_Data_Store_CPT extends WC_Data_Store_WP implements WC_Object_Da
wp_cache_delete( $product_id_with_stock, 'post_meta' );
}
/**
* Update a product's sale count directly.
*
* Uses queries rather than update_post_meta so we can do this in one query for performance.
*
* @since 2.7.0 this supports set, increase and decrease.
* @param int
* @param int|null $quantity
* @param string $operation set, increase and decrease.
*/
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' :
$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' :
$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 :
$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' );
}
/**
* Update a products average rating meta.
*

View File

@ -99,7 +99,19 @@ interface WC_Product_Data_Store_Interface {
* @param int|null $stock_quantity
* @param string $operation set, increase and decrease.
*/
function update_product_stock( $product_id_with_stock, $stock_quantity = null, $operation = 'set' );
public function update_product_stock( $product_id_with_stock, $stock_quantity = null, $operation = 'set' );
/**
* Update a product's sale count directly.
*
* Uses queries rather than update_post_meta so we can do this in one query for performance.
*
* @since 2.7.0 this supports set, increase and decrease.
* @param int
* @param int|null $quantity
* @param string $operation set, increase and decrease.
*/
public function update_product_sales( $product_id, $quantity = null, $operation = 'set' );
/**
* Get shipping class ID by slug.

View File

@ -754,9 +754,9 @@ function wc_update_total_sales_counts( $order_id ) {
if ( sizeof( $order->get_items() ) > 0 ) {
foreach ( $order->get_items() as $item ) {
if ( $product = $item->get_product() ) {
$product->set_total_sales( $product->get_total_sales() + absint( $item['qty'] ) );
$product->save();
if ( $product_id = $item->get_product_id() ) {
$data_store = WC_Data_Store::load( 'product' );
$data_store->update_product_sales( $product_id, absint( $item['qty'] ), 'increase' );
}
}
}