Automattic\WooCommerce\Caches

ProductCountCacheService::update_on_product_status_changedpublicWC 1.0

Update the cache whenever a product status changes.

Method of the class: ProductCountCacheService{}

No Hooks.

Returns

null. Nothing (null).

Usage

$ProductCountCacheService = new ProductCountCacheService();
$ProductCountCacheService->update_on_product_status_changed( $new_status, $old_status, $post ): void;
$new_status(string) (required)
The new post status.
$old_status(string) (required)
The previous post status.
$post(WP_Post) (required)
The post object.

ProductCountCacheService::update_on_product_status_changed() code WC 11.0.0

public function update_on_product_status_changed( string $new_status, string $old_status, WP_Post $post ): void {
	if ( 'product' !== $post->post_type ) {
		return;
	}

	$product_id = $post->ID;

	// WordPress uses 'new' as old_status exclusively on the first transition_post_status of a newly inserted post.
	if ( 'new' === $old_status ) {
		$this->products_in_creation[ $product_id ] = true;
	}

	$is_new_cached = $this->product_count_cache->is_cached( 'product', $new_status );
	$is_old_cached = $this->product_count_cache->is_cached( 'product', $old_status );
	if ( ! $is_new_cached && ! $is_old_cached ) {
		return;
	}

	// If the status count has already been incremented for this product, skip.
	if ( ( $this->product_statuses[ $product_id ] ?? null ) === $new_status ) {
		return;
	}

	$previously_tracked                    = isset( $this->product_statuses[ $product_id ] );
	$this->product_statuses[ $product_id ] = $new_status;
	$was_decremented                       = $is_old_cached && false !== $this->product_count_cache->decrement( 'product', $old_status );
	if ( $is_new_cached ) {
		$this->product_count_cache->increment( 'product', $new_status );
	}

	// Record old status for creation-time correction only; existing-product decrements are correct and must not be reversed.
	// If $previously_tracked, an earlier transition already counted the old status — decrement is legitimate.
	if ( ! $previously_tracked && $was_decremented && ! isset( $this->initial_product_statuses[ $product_id ] ) && isset( $this->products_in_creation[ $product_id ] ) ) {
		$this->initial_product_statuses[ $product_id ] = $old_status;
	} elseif ( ( $this->initial_product_statuses[ $product_id ] ?? null ) === $new_status ) {
		unset( $this->initial_product_statuses[ $product_id ] );
	}
}