How to display number of item in cart and cart total amount Woocommerce | themelocation

How to display number of item in cart and cart total amount?

In this tutorial we’ll learn how to display number of items in cart and cart total. This can be done easily with the help of following lines of code.

<?php global $woocommerce; ?>

 <a class="cart-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>">
 <?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> - <?php echo $woocommerce->cart->get_cart_total(); ?>

</a>

You can place it anywhere in your theme’s files where you want to display it.

So, for the example purpose we’ll add this to header.php file just below the navigation menu.

You can access header.php file here:

woocommerce

No add the code right after navigation menu (Add the Code anywhere in the file):

woocommerce

After adding code update the file and refresh the front end of site. You’ll see cart count and total something like this is added to your header.

woocommerce

Now, let’s add some product to cart and see for changes. I’m going to add a product to cart and after adding to cart here is what my header look like:

woocommerce

There is still a loop hole, the cart viewer will not be updated if we add products to cart using ajax.

Here in the following images you can see that cart viewer being displayed same count and total before and after adding a product to cart.

woocommercewoocommerce

Now to overcome this, add the following lines of code at the end of your theme’s functions.php file:

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-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>"><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> - <?php echo $woocommerce->cart->get_cart_total(); ?></a>

                <?php 

                $fragments['a.cart-contents'] = ob_get_clean();

                return $fragments; 

}

Save the file and add the products you’ll see the change in cart viewer even after products being added via ajax.

woocommerce

2 Responses to How to display number of item in cart and cart total amount?

  1. faruk April 27, 2016 at 9:18 am #

    Really awesome tutorial.*****please I want more tutorial
    I

  2. Abhijit October 21, 2016 at 6:51 am #

    HEY !!!!!!!!! MAN,

    YOUR GREAT AND YOU CAN SOLVE MY PROBLEM

Leave a Reply