Automattic\WooCommerce\Internal\Utilities
InCartQuantity::for_product
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.
Method of the class: InCartQuantity{}
No Hooks.
Returns
int|float. The sum of eligible cart-item quantities.
Usage
$result = InCartQuantity::for_product( $product_id );
- $product_id(int) (required)
- Product or variation ID to count.
Changelog
| Since 11.3.0 | Introduced. |
InCartQuantity::for_product() InCartQuantity::for product code 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;
}