Web & Software Developer

3 Steps To Add WooCommerce Cart Icon With Cart Count To Your Theme’s Header

These are 3 steps to add a WooCommerce cart icon with the cart count to your theme. The number of items will be updated automatically 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.

  1. Add the HTML to your theme’s template file where you want the cart icon to appear. The cart icon will only appear if WooCommerce is active.

    <?php if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    
    	$count = WC()->cart->cart_contents_count;
    	?><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
    	}
            ?></a>
    
    <?php } ?>
    
    

    You can either add the above directly into your theme template, or you can add it with one of your theme’s template hooks. For example, if your theme’s header has a hook like, do_action( 'your_theme_header_top' );, then you can add the above code to your functions file like this:

    /**
     * Add Cart icon and count to header if WC is active
     */
    function my_wc_cart_count() {
    
    	if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    
    		$count = WC()->cart->cart_contents_count;
    		?><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
    		}
                    ?></a><?php
    	}
    
    }
    add_action( 'your_theme_header_top', 'my_wc_cart_count' );
    
    
  2. Add the following to your functions. This ensures the cart will be updated immediately as items are added to the cart.

    /**
     * Ensure cart contents update when products are added to the cart via AJAX
     */
    function my_header_add_to_cart_fragment( $fragments ) {
    
    	ob_start();
    	$count = WC()->cart->cart_contents_count;
    	?><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			
    	}
            ?></a><?php
    
    	$fragments['a.cart-contents'] = ob_get_clean();
    	
    	return $fragments;
    }
    add_filter( 'woocommerce_add_to_cart_fragments', 'my_header_add_to_cart_fragment' );
    
    
  3. Add this CSS to use WooCommerce’s native shopping cart icon. Adjust as needed to fit nicely into your theme. You can also use your own icon from a custom icon font. To use a different icon, change ‘WooCommerce’ to the name of your icon font, and change the e01d on line 3 to your icon’s Unicode. For example, if you already use Font Awesome, change line 2 to font-family:FontAwesome;, and line 3 to content: "\f07a"; to use Font Awesome’s cart icon.

    See how to add CSS.

    Also, you may want to edit line 15 and 16 below to change the color of the cart count and background color of the bubble.

    .cart-contents:before {
    	font-family:WooCommerce;
    	content: "\e01d";
    	font-size:28px;
    	margin-top:10px;
    	font-style:normal;
    	font-weight:400;
    	padding-right:5px;
    	vertical-align: bottom;
    }
    .cart-contents:hover {
        text-decoration: none;
    }
    .cart-contents-count {
        color: #fff;
        background-color: #2ecc71;
        font-weight: bold;
        border-radius: 10px;
        padding: 1px 6px;
        line-height: 1;
        font-family: Arial, Helvetica, sans-serif;
        vertical-align: top;
    }
    

That’s it. Preview your store and add items to the cart to see this in action.

By

We've 54 Responses

  1. November 12th, 2015 at 9:57 am

    Thanks! It gave me the right direction for what I wanted. I’ve used it along with some refs. on storefront and now I have my cart widget working sweet as on storefront 🙂

    avatar
  2. April 12th, 2016 at 6:36 am

    Hi

    I simply want to use section 3 in my functions file to change my icon, I have changed it to FontAwesome and put the correct code in.

    My site already has a top bar with a mini cart in and its that icon i am trying to change?

    Any help would be gladly received!

    avatar
    • April 13th, 2016 at 4:00 pm

      You’d have to change the CSS selector “.cart-contents” to match and override the one for your existing icon. You can see that in your browser by hovering over the icon, right-clicking, and “Inspect Element.”

      avatar
  3. June 15th, 2016 at 2:19 pm

    thanks Isabel, I found this very useful and a good starting point for looking at adding the mouseover cart fragment (the drop down div that appears on many themes)

    avatar
  4. July 2nd, 2016 at 4:00 am

    Olá, muito obrigado por dispor seu código. Você é uma excelente Dev.

    Hi, Thank you for your code, you is a excellent Developer 🙂

    avatar
  5. August 28th, 2016 at 11:46 am

    Isabel,

    This article is awesome and it saved me a lot of time. For some reason this segment caused some issues as it was ‘t work so I had to remove it

    <?php if ( $count > 0 ) echo '(' . $count . ')'; ?>

    And it still works fine. Just one question though. How can we style the number of items so they appear as a bubble on the cart?

    Many thanks and regards,

    Pradeep

    avatar
  6. November 4th, 2016 at 10:26 am

    This works great however the cart shows up on every page in Firefox (which is what I want) but only on the woocommerce related pages in Chrome and Safari. Any idea on how to make sure it shows up on every page?

    avatar
  7. January 27th, 2017 at 7:53 am

    Hi. I use that code and love it. I have noticed recently that sometimes when I’m entering my site (from different browsers and ip’s) there green indicator is showing 1 item in the cart. After entering the cart there is no item.

    I use Autoptimize and WP Super Cache. Do You know if maybe this can be a potential problem?

    avatar
    • January 27th, 2017 at 2:15 pm

      Autoptimize would not cause a problem with this. The cache is an issue. I’ve never used WP Super Cache, I use Hyper Cache, and I always add the WooCommerce Cart page, and the Checkout page, and product pages to the “List of URIs to Bypass” in the cache settings, like this:

      /cart/
      /cart
      /checkout/
      /checkout
      /product/
      /product
      

      This means that those pages will not be cached. This eliminates errors with the WooCommerce cart, for me. I have found, in my cases, that WooCommerce doesn’t work well with cache plugins. If you don’t mind having those pages not cached, then try adding that list to the WP Super Cache settings, if they have a setting for “Bypassing the cache.”

      avatar
    • February 10th, 2017 at 3:12 pm

      Short answer: no.

      This code doesn’t include any AJAX/jQuery/JavaScript that do the actual work. WooCommerce core does the actual work: WooCommerce runs their AJAX script anyway when items are added to the cart. (My code here simply adds the necessary HTML elements to capture their AJAX response for the cart count.)

      But WooCommerce doesn’t use admin-ajax.php for adding the items to the cart. They created their own AJAX endpoints, and the one they use here is ?wc-ajax=add_to_cart instead of admin-ajax.php.

      Hope that helps.

      avatar
      • February 11th, 2017 at 6:51 pm

        Thank you Isabel for the quick clarifications.

        One final query, How do I remove the brackets around the counter? When I insert your code snippets, I see the following in cart: (5).

        Thanks again. You are awesome!

        avatar
        • February 13th, 2017 at 9:17 am

          Thank you. This code doesn’t add any brackets. I am guessing that your theme (or plugin) is possibly adding a filter for the cart count, to add the brackets. If you find this somewhere in your theme: woocommerce_cart_contents_count, that would be modifying the cart count.

          avatar
          • February 16th, 2017 at 12:45 pm

            Thanks for the response. This solution works great!
            …but with W3TC cache plugin and cloudflare installed, most of the pages do not display the correct count (- display 0). I’ve only excluded cart page from cache, therefore it displays correctly. I cannot exclude header.php in w3tc cache plugin.

            Any ideas? your thoughts? Thank you

            avatar
    • June 12th, 2018 at 2:46 pm

      I was able to get it to work by removing the if statement to check if the plugin was active. I’m guessing that php would be different in a multisite setup. Just use the code like this:

      <?php  
          $count = WC()->cart->cart_contents_count;
          ?><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
          }
              ?></a>
      
      avatar
  8. March 7th, 2017 at 10:56 pm

    I do not understand how to do this from storefront theme. I’m a developer, just not WP one. Any help? I thik i just need to know what hooks to use.

    avatar
    • March 8th, 2017 at 11:14 pm

      I don’t have experience with the Storefront theme, but doesn’t it have its own shopping basket icon? I took a look, and you can use the storefront_header hook. So, you can add this to the Storefront theme by using the second example from #1, above, but change line 19 to this:

      add_action( 'storefront_header', 'my_wc_cart_count', 25 );

      If you want to align it to the top-right corner, add this CSS:

      a.cart-contents { float: right;padding-left: 3px; }
      

      Hope that helps.

      avatar
      • March 9th, 2017 at 9:58 pm

        I briefly tried that with no luck. This already had worked for me anyways.

        functions.php:

        
        /* Cart icon with order count. Override default implementation. */
        function storefront_header_cart() {
            ?>
            <div class="site-header-cart"><a class="cart-content cart-customlocations" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>">
                    <span class="cart-content-count"><?= WC()->cart->cart_contents_count; ?></span></a></div>
        <?php }
        
        
        // Ensure cart contents update when products are added to the cart via AJAX (place the following in functions.php).
        // Used in conjunction with https://gist.github.com/DanielSantoro/1d0dc206e242239624eb71b2636ab148
        add_filter('add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment');
        
        function woocommerce_header_add_to_cart_fragment( $fragments ) {
            global $woocommerce;
        
            ob_start();
        
            ?>
            <a class="cart-content cart-customlocations" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>">
                <span class="cart-content-count"><?= $woocommerce->cart->cart_contents_count; ?></span></a>
            <?php
        
            $fragments['a.cart-customlocations'] = ob_get_clean();
        
            return $fragments;
        

        And a customized version of your css.

        avatar
          • March 23rd, 2017 at 7:17 pm

            /*adjusting default margins and paddings*/
                #masthead .site-header-cart .cart-content {
                    display: block;
                    padding: 1.3em 0;
                }
            
                /* Cart */
                #masthead .site-header-cart .cart-content:before {
                    position: relative;
                    bottom: 12px;
                    margin-top: 10px;
                    padding-right: 5px;
                    color: #fff;
                    content: "\f07a";
                    font-family: FontAwesome;
                    font-style: normal;
                    font-weight: 400;
                    font-size: 20px;
                    vertical-align: bottom;
                }
            
                #masthead .site-header-cart .cart-content:hover {
                    text-decoration: none;
                }
            
                #masthead .site-header-cart .cart-content-count {
                    padding: 1px 5px;
                    border-radius: 10px;
                    line-height: 1;
                    vertical-align: top;
                    color: #fff;
                    background-color: #EC7A5C;
                    font-family: Arial, Helvetica, sans-serif;
                    font-weight: bold;
                    font-size: 12px;
                }
            
            avatar
  9. March 22nd, 2017 at 6:36 am

    Hello,

    This is the snippet that worked for me in Strore Front. Yes. It already has its own cart but I prefer this one. Perhaps someone else might find it useful, as well.

    /**
     * Add Cart icon and count to header if WC is active
     */
    function my_wc_cart_count() {
     
        if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
     
            $count = WC()->cart->cart_contents_count;
            ?><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
            }
                    ?></a><?php
        }
    }
    add_action( 'storefront_header', 'my_wc_cart_count', 43 );
    
    /**
     * Ensure cart contents update when products are added to the cart via AJAX
     */
    function storefront_header_add_to_cart_fragment( $fragments ) {
     
        ob_start();
        $count = WC()->cart->cart_contents_count;
        ?><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            
        }
            ?></a><?php
     
        $fragments['a.cart-contents'] = ob_get_clean();
         
        return $fragments;
    }
    add_filter( 'woocommerce_add_to_cart_fragments', 'storefront_header_add_to_cart_fragment' );
    
    avatar
  10. April 6th, 2017 at 9:28 pm

    Hi Isabel thanks for this site!

    I’m in a slightly different scenario… I have setup an online menu using the WPPIZZA plugin (X-theme)
    I pretty much have the shopping and checkout experience looking and working the way I want, but I still want the cart icon (in the nav bar) to display the total number of products added.

    How can I do this without disrupting the work I’ve done?

    I have Woocommerce installed, but do not know much about it.

    I will have at least 4 menu pages, ( all should display the cart) but only one is active now: http://colorsstudios.com/?page_id=3230

    Note: There is a shopping cart in the side bar which is visible on wide displays, so this functionality is mostly for mobile users, although I wish to have it visible on all platforms.

    avatar
    • June 5th, 2017 at 7:46 pm

      You can add text after the number by inserting this (note the singular “item” and plural “items”):

      $count .= ( '1' == $count ) ? ' item' : ' items';

      This must be inserted into the beginning of line 6, in code block Number 1. Also, into the beginning of line 10, in Number 2.

      avatar
  11. May 22nd, 2017 at 3:53 pm

    Do you know how you can display 0 if there are no items in the cart?

    I changed

    <?php 
    									if ( $count > 0 ) {
    										?>
    										<span class="cart-contents-count"><?php echo esc_html( $count ); ?></span>
    

    to

    <?php 
    									if ( $count >= 0 ) {
    										?>
    										<span class="cart-contents-count"><?php echo esc_html( $count ); ?></span>
    

    And the zero shows up momentarily, and then disappears like some jquery removes it from the DOM. I’m guessing this is some js in woocom?

    avatar
    • June 5th, 2017 at 7:34 pm

      Did you make the change in both places? if ( $count > 0 ) { needs to be changed in both places: code block Number 1, line 5, and code block Number 2, line 9. Hope that helps.

      avatar
  12. February 25th, 2018 at 3:52 pm

    Thank you, works out of the box … I made my own HTML/CSS modifications and missed the note about keeping both files’ markup in the same state so the cart count wouldn’t update.

    Clear and simple – much appreciated!

    avatar
  13. April 3rd, 2018 at 5:23 pm

    WC()->cart->get_cart_url() is deprecated, use wc_get_cart_url() instead

    Also I chose to link to the shop page if cart is empty:

    href="<?php echo $count > 0 ? wc_get_cart_url() : get_permalink( wc_get_page_id( 'shop' ) ); ?>"
    
    avatar

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]