logo

Programmatically count the number of products in the cart Drupal Commerce 10

17
February

Programmatically count the number of products in the cart Drupal Commerce 10
By: Anonymous | Published On: Mon, 02/17/2025 - 18:27

p>In Drupal Commerce 10, you can programmatically count the number of products in the cart. Below is an example of how you can achieve this using Drupal’s Commerce API.

 

use Drupal\commerce_order\Entity\Order;
	$store_id = 1;
    $order_type = 'default';
    $cart_manager = \Drupal::service('commerce_cart.cart_manager');
    $cart_provider = \Drupal::service('commerce_cart.cart_provider');
    $entity_manager = \Drupal::entityTypeManager();
    $store = $entity_manager->getStorage('commerce_store')->load($store_id); 
    $cart = $cart_provider->getCart($order_type, $store);
	if(!empty($cart)){
		$total_items = count($cart-> getItems());
	}

Need Help ?