Automattic\WooCommerce\Internal\Utilities

InCartQuantity::for_product │ public static │ WC 11.3.0

Sum the product's quantity in the published cart, excluding declared child lines. Reads the cart that BlocksSharedState::load_cart_state() publishes, so call it after that. An entry without an id key, such as the [] placeholder, matches nothing.

Метод класса: InCartQuantity{}

Хуков нет.

Возвращает

int|float. The sum of eligible cart-item quantities.

Использование

$result = InCartQuantity::for_product( $product_id );
$product_id(int) (обязательный)
Product or variation ID to count.

Список изменений

С версии 11.3.0 Введена.

Код InCartQuantity::for_product() WC 11.3.0

public static function for_product( int $product_id ) {
	$woocommerce_state = wp_interactivity_state( 'woocommerce' );
	$total             = 0;

	foreach ( $woocommerce_state['cart']['items'] ?? array() as $item ) {
		if ( ( $item['id'] ?? null ) !== $product_id || '' !== ( $item['parent_item_key'] ?? '' ) ) {
			continue;
		}

		$total += $item['quantity'];
	}

	return $total;
}