Woocommerce Cart Icon With Count

Dec 13, 2016
WooCommerce snippets

Use this snippet to add a WooCommerce cart icon with the cart count to your theme. The number of items will be updated automatically with AJAX as items are added to cart.

To avoid errors, this will first check if WooCommerce is active. That way, it doesn’t hurt to add this to any theme regardless of whether WooCommerce plugin is active or not.

<?php if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {       
$count = WC()->cart->cart_contents_count; ?>
  <div id="woo-cart-button">
    <a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>">
    <?php if ( $count > 0 ) { ?>         
      <span class="cart-contents-count"><?php echo esc_html( $count ); ?></span>         
    <?php } ?>
<?php } ?>

In order to make it AJAX updated, you should place this to your theme functions.php

add_filter('add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment');

function woocommerce_header_add_to_cart_fragment( $fragments ) {
  global $woocommerce;

  ob_start(); ?>
  <span class="cart-contents-count"><?php echo $woocommerce->cart->cart_contents_count; ?></span>
  <?php $fragments['span.cart-contents-count'] = ob_get_clean();

  return $fragments;


No comments

Leave a Reply

Your email address will not be published. Required fields are marked *