WC_Product_Data_Store_CPT::update_product_sales( int $product_id, int|null $quantity = null, string $operation = 'set' )

Update a product’s sale count directly.


Description Description

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


Parameters Parameters

$product_id

(Required) Product ID.

$quantity

(Optional) Quantity.

Default value: null

$operation

(Optional) set, increase and decrease.

Default value: 'set'


Top ↑

Source Source

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

1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
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 );
}

Top ↑

Changelog Changelog

Changelog
Version Description
3.0.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

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