1

For his cart, my client wants a cart icon with the number of items in it. Not a list of all items. I searched around a little bit but didn't find anything.

3 Answers 3

0

Assuming the ubercart core 'shopping cart' block doesn't work for what you need:

enter image description here

Then you'll need to output it in your theme or create it as your own custom block. Use the uc_cart_get_contents() function. This loads an array of all the items in their cart, which allows you to get a quick count() on to get your number. From there it is trivial to overlay this output on to your cart icon.

// Load the current shopping cart.
$items = uc_cart_get_contents();

// Display a message if the cart has more than 5 products.
$item_count = count($items);

print "<span class='count'>$item_count</span><img src='your_cart_icon.gif'>";
3
  • Thanks. One more thing... If i want the block to display only if there's one or more items in it?
    – P.Roy
    Commented Mar 15, 2016 at 15:48
  • use count() again but wrap it in an if statement, ex. if (count($items)) then print the cart, otherwise do nothing.
    – schnippy
    Commented Mar 15, 2016 at 16:54
  • sorry i'm not very good with php. I did the following but it didn't work: <?php // Load the current shopping cart. $items = uc_cart_get_contents(); // Display a message if the cart has more than 5 products. $item_count = count($items); if (count($items)); print "<div class='my-cart'><a href='/cart'>Panier d'achat <i class='fa fa-cart-plus'></i> <span class='count'>$item_count</span><span class='count'></span></a></div>"; ?>
    – P.Roy
    Commented Mar 23, 2016 at 16:07
1

As for D8 latest version, it looks like uc_cart_get_contents is not working anymore. So here is how I managed to do it :

/** @var \Drupal\uc_cart\CartManager $cartManager */
$cartManager = \Drupal::service('uc_cart.manager');
$items = $cartManager->get()->getContents();
$variables['nbr_cart_items'] = count($items);
1

The code supplied works "OK" as a quick fix, but it actually counts the number of distinct products in the shopping cart, not the number of items.

Here's a snippet that counts the number of items using a different Ubercart function than the one employed above: uc_cart_get_total_qty()

if (module_exists('uc_cart')) {
  $cart_item_count = uc_cart_get_total_qty();
  print $cart_item_count;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.