How do I count the number of products in cart programmatically?
In Drupal 8, carts are special orders, related to a user (like regular orders). In a custom module, you can fetch the logged in user orders, filter them by a convenient boolean field called 'cart', sort them by creation date to get the last cart for this user. Then you can get the items count for this cart order :

in mymodule.module :

use Drupal\commerce_order\Entity\Order;

function mymodule_preprocess_[page|block|something_else](&amp;$variables) {

  // get orders...
  $query = \Drupal::entityQuery('commerce_order')
    // ...for logged in user, could be anonymous (uid = 0)
    -&gt;condition('uid',\Drupal::currentUser()-&gt;id())
    // ...which are carts
    -&gt;condition('cart', 1)
    // ...last created first
    -&gt;sort('created', 'DESC')
    // ...get only one
    -&gt;range(0,1);

  // execute this : you get an array of a unique order ids (last cart)
  $cartsOrders = $query-&gt;execute();

  // I found one : this user has a cart
  if(count($cartsOrders) &gt; 0) {

    // load the order which is the last cart for logged in user
    /* @var Order $lastCart */
    $lastCart = current(Order::loadMultiple($cartsOrders));
    // send this order items count to the template
    // ({{ cartItemsCount }} in your twig)
    $variables['cartItemsCount'] = count($lastCart-&gt;getItems());
  }
}


This may contains non optimal or ugly code, this is just a starting point (but quickly tested though, seems to work). Also this need to be tested in rare case scenarios or weird situations (involving anonymous users for example). My strategy (grab the last created cart order) may be wrong too...I would be happy to have a specialist feedback on this.

EDIT

I spent more time on this and had to debug a few things, here is some improvments (more Drupal Commerce 2 way) :

/* @var CurrentStoreInterface $cs */
$cs = \Drupal::service('commerce_store.current_store');
/* @var CartProviderInterface $cpi */
$cpi = \Drupal::service('commerce_cart.cart_provider');
$cart = $cpi-&gt;getCart('default', $cs-&gt;getStore());

$nbItemsInCart = $cart ? count($cart-&gt;getItems()) : 0;