0

I'm working on a Woocommerce theme and I need to grab just the number of items in my cart without any totals or other markup. I've tried using

  <?php echo WC()->cart->get_cart_contents_count(); ?>

But it returns two spans span.amount and span.count and inside span.count it has the string "items" as well

Is there a way to return just the number of items in my cart, preferably as an int?


UPDATE:

So when using the following code:

 <a class="cart-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>">
    <?php echo WC()->cart->get_cart_contents_count(); ?>
 </a>

The extra markup above was returned but, by commenting out the anchor tags like so:

<!-- <a class="cart-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>"> -->
    <?php echo WC()->cart->get_cart_contents_count(); ?>
  <!-- </a> -->

Only an int was returned.

Why is that?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
ChadTheDev
  • 399
  • 3
  • 13
  • Sorry but the `cart->get_cart_contents_count(); ?>` output's an integer… see the [documentation for `WC_Cart` `get_cart_contents_count()` method](https://docs.woocommerce.com/wc-apidocs/source-class-WC_Cart.html#657-664) … as you will see: `* @return int` – LoicTheAztec Feb 28 '19 at 23:41
  • Interesting, so I fixed the problem but I still don't understand why, see above.... – ChadTheDev Feb 28 '19 at 23:53
  • Because this is the cart icon with count (and cart amount) that is ajax cached via cart fragments on the span class "cart-contents"… So when you comment the html it displays only an integer of the count. But if you use ajax add to cart, the count is not updated this way… see [this thread](https://stackoverflow.com/a/51126271/3730754) o better understand. – LoicTheAztec Mar 01 '19 at 00:03

0 Answers0