Sara asked in Genesis WordPress Facebook group,
Does anyone know of a good tutorial on how to add a shopping cart that display the number of items and total using WooCommerce. I want it to function similar to this plugin but I do not want to use a plugin. Thanks http://wordpress.org/plugins/woocommerce-menu-bar-cart/
In this article I share the code extracted from Woocommerce Menu Cart plugin that can be placed in active theme’s functions.php which would display the number of items in shopping cart and their total value in Primary navigation menu at the right side.
When there are no items in the cart, nav bar is going to look like this:
“0 items – $0” links to WooCommerce Shop Base Page, typically http://example.com/shop/
When there is at least 1 item in the cart, nav bar will look this:
Clicking on “2 items – $47” in this example takes the visitor to Cart page, http://example.com/cart/
Add this in functions.php:
//* Make Font Awesome available | |
add_action( 'wp_enqueue_scripts', 'enqueue_font_awesome' ); | |
function enqueue_font_awesome() { | |
wp_enqueue_style( 'font-awesome', '//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css' ); | |
} | |
/** | |
* Place a cart icon with number of items and total cost in the menu bar. | |
* | |
* Source: http://wordpress.org/plugins/woocommerce-menu-bar-cart/ | |
*/ | |
add_filter('wp_nav_menu_items','sk_wcmenucart', 10, 2); | |
function sk_wcmenucart($menu, $args) { | |
// Check if WooCommerce is active and add a new item to a menu assigned to Primary Navigation Menu location | |
if ( !in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) || 'primary' !== $args->theme_location ) | |
return $menu; | |
ob_start(); | |
global $woocommerce; | |
$viewing_cart = __('View your shopping cart', 'your-theme-slug'); | |
$start_shopping = __('Start shopping', 'your-theme-slug'); | |
$cart_url = $woocommerce->cart->get_cart_url(); | |
$shop_page_url = get_permalink( woocommerce_get_page_id( 'shop' ) ); | |
$cart_contents_count = $woocommerce->cart->cart_contents_count; | |
$cart_contents = sprintf(_n('%d item', '%d items', $cart_contents_count, 'your-theme-slug'), $cart_contents_count); | |
$cart_total = $woocommerce->cart->get_cart_total(); | |
// Uncomment the line below to hide nav menu cart item when there are no items in the cart | |
// if ( $cart_contents_count > 0 ) { | |
if ($cart_contents_count == 0) { | |
$menu_item = '<li class="right"><a class="wcmenucart-contents" href="'. $shop_page_url .'" title="'. $start_shopping .'">'; | |
} else { | |
$menu_item = '<li class="right"><a class="wcmenucart-contents" href="'. $cart_url .'" title="'. $viewing_cart .'">'; | |
} | |
$menu_item .= '<i class="fa fa-shopping-cart"></i> '; | |
$menu_item .= $cart_contents.' - '. $cart_total; | |
$menu_item .= '</a></li>'; | |
// Uncomment the line below to hide nav menu cart item when there are no items in the cart | |
// } | |
echo $menu_item; | |
$social = ob_get_clean(); | |
return $menu . $social; | |
} |
If you would like to add the cart menu item to a custom menu assigned to Secondary Navigation Menu, change primary to secondary in line 21.
If you would like cart menu to appear only when there is at least 1 item in the cart, then uncomment lines 34 and 46.
Reference: http://www.billerickson.net/customizing-wordpress-menus/
Credit: https://wpovernight.com/
Works perfectly thanks so much 🙂
Thanks, Sridhar! Can you give any guidance on how to make this work in a custom menu? A lot of Genesis child themes use the header right widget area for the main navigation menu.
Follow http://www.sridharkatakam.com/adding-content-custom-menu-header-genesis-using-genesis-header-nav-plugin/
You’re a star! Thanks very much, Sridhar.
Hi Sridhar
I too would like to place this feature in a custom menu. The custom menu would be placed in a custom widget area.
Many thanks
Dale
[…] For some background and details of what the code below does, refer to my earlier post titled Adding a cart icon with number of items and total cost in nav menu when using WooCommerce. […]
Is there a way to get this code to append to my secondary menu at the beginning (instead of the end, where it currently adds itself)?
Thanks!
How am I suppose to change this if I’m NOT using WooCommerce. Say, if I’m using WP Simple Paypal Shopping Cart and I want the button in the menu? Do I change everywhere it says WooCommerce to WP Simple?
Thanks
Booyah! Worked perfectly! Thanks so much…. this is much better than adding a whole new plugin.
want to show cart icon with number of items and total cost in .my-extra-widget
what changes should i make
just take some plugin like WooCart Pro or WP Cart Widget 🙂
You can create your own widget by register widget function http://codex.wordpress.org/Function_Reference/register_widget
Copy example code
change name of widget
then add code from line no 25 to 47 in widget function….
You will see your widget in admin panel -> widgets
5.. Add wherever you want
If using Mystile, change “primary” to “primary-menu” in line 21.
Dude thanks for this one good article. You saved my time. Also my wp installation from having one more plugin… I always try to use minimum plugins.
Thanks for the code! Instead of ‘Item’ or ‘Items’, I would like it to say ‘Cart’. I can see in the code where I can change the name.
But I don’t want the ‘0’ to appear in front of the cart if there’s nothing in it. I still want the ‘Cart’ link to show.
I’m looking for some code that will display the cart exactly like this;
Nothing in it; Cart
Something in the cart: Cart (2) $32.98
Do you know how I can manipulate the above code to get it to appear exactly like above?
Thank you so much.
I am a beginner, how do I get this function to print?
Hi
Great idea, works for non-ajax add-to-cart as the page is refreshed. Does not work when ajax used UNTIL the page is refreshed. Is there any way to get the menu refreshed via ajax as well?
Thanks
Steve, that’s exactly what I was going to ask too. I really like this, but without AJAX it just appears broken. What a shame.
Guys, You have to write ajax fuction saperately to work.
This code only work when page loads. If you see woocommerce mini cart. when any product added via ajax, it is immediately added in minicart without page refresh. So woocommerce written code for that. But woocommerce didnt write any ajax for this above code. As this is custom code written on custom requirement. You have to write it at condition of ajax completes, you have to fire your own ajax code to refresh above code.
http://api.jquery.com/ajaxcomplete/
Hi Makarand, thanks for the clarification, maybe you could also make it clear in the article that ajax is not a built-in function.
@ David – I got ajax working by using the original plugin woocommerce-menu-bar-cart and adapting it to my needs, instead of using custom fuctions.php code.
@Makarand – Thanks too. I will check that out.
@Steve Yes, just after writing this my brains cells fired up again and I found the actual plugin. It works great and was easy to stop it loading the extra stylesheets.
@Steve
Could you maybe share the adaptations you have made to make the AJAx script work?
Thank you,
Igor
@Igor
Put the following code into your functions.php if you want to update both cart items and value without page refresh –
add_filter( ‘woocommerce_add_to_cart_fragments’, ‘woocommerce_header_add_to_cart_fragment’ );
function woocommerce_header_add_to_cart_fragment( $fragments ) {
ob_start();
?>
<a class="wpmenucart-contents" href="cart->get_cart_url(); ?>” title=””>cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> – cart->get_cart_total(); ?>
<?php
$fragments['a.wpmenucart-contents'] = ob_get_clean();
return $fragments;
}
I missed closing a tag. Here is the complete code –
add_filter( ‘woocommerce_add_to_cart_fragments’, ‘woocommerce_header_add_to_cart_fragment’ );
function woocommerce_header_add_to_cart_fragment( $fragments ) {
ob_start();
?>
<a class="wpmenucart-contents" href="cart->get_cart_url(); ?>” title=””>cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> – cart->get_cart_total(); ?>
Hi, this is great! How can I change the color of the cart details on the menu… I want the color to be different from the other menu sections so that it can easily be distinguished right away…
Thanks a lot!
Working Great!
Thanks Sridhar
Great tutorial, if you are looking to do this and have Roots / Sage based template there is a quick snippet on how to do this here https://fabriceleven.com/dev/adding-woocommerce-checkoutcart-links-nav-bar/
Hi,
Thanks for this article. I have all the above working, however I want that when a customer hovers over the cart the items appear. do you have any idea how that could be done?
thanks for your help!
Hi, how can i auto-refresh my menu cart content, via ajax, when client add product to cart?
I was trying to add $fragments from this:
https://docs.woothemes.com/document/show-cart-contents-total/
But its don’t work properly, thanks 🙂
thanks alot it works like a charm
thank you so much , work properly, thanks again
Has anybody been able to get this to work with W3 Total Cache? I’m getting inconsistent cart totals from page to page.
How can i insert the AJAX functionality from the main plugin into the functions.php from my child-theme? What files do i need and what changes do i need to make?
Hello,
I used your solution and it’s worked. But the problem is the cart is not updating automatically. When I refreshed the site the cart shows updated total. Can you please help me to showing the updated cart total after clicking “Add to Cart” button.
Thanks.
you’re the man! Thanks so much
Hello,
Can you help me please to create an drop down cart in my menu?
I dont want to use plugin. I love your code but can you help me?
I added this code to my functions.php file, saved it, refreshed on the front end, and nothing changed at all. Any idea why that might be? I have 3 items in my cart… Instead of the primary nav menu, how can I make it add the cart menu item to the top menu?
What a great bit of code. Many thanks.
Hi there,
This works great initially, but unless the page reloads the menu total doesn’t update. For example, if I click “add to cart” from the initial products overview page (not product details page) it doesn’t update the menu total. I added this code, but it still doesn’t refresh without a page refresh. Is there a way to fix this? [code]add_filter( ‘woocommerce_add_to_cart_fragments’, ‘woocommerce_header_add_to_cart_fragment’ );
function woocommerce_header_add_to_cart_fragment( $fragments ) {
ob_start();
?>
get_cart_url(); ?>” title=””>cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> – cart->get_cart_total(); ?>
<?php
$fragments['a.wpmenucart-contents'] = ob_get_clean();
return $fragments;
}[/code]
I’m having the same issue and working on a solution now. The trick is to hook into the javascript event “added_to_cart” after the button is pressed. I think I need to extract the cart quantity and total from the fragments array.
jQuery( function( $ ) {
$( document.body ).on( “added_to_cart”, function( event, fragments, cart_hash, thisbutton ) {
console.log(fragments);
console.log(thisbutton);
});
});
Ok you need to add the following code to your functions.php file. This will update the fragments and show the updated quantity and price.
/**
* Ensure cart contents update when products are added to the cart via AJAX
* https://docs.woocommerce.com/document/show-cart-contents-total/
*/
add_filter( ‘woocommerce_add_to_cart_fragments’, ‘woocommerce_header_add_to_cart_fragment’ );
function woocommerce_header_add_to_cart_fragment( $fragments ) {
ob_start();
?>
<a class="cart-contents" href="cart->get_cart_url(); ?>” title=””>cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> – cart->get_cart_total(); ?>
<?php
$fragments['a.cart-contents'] = ob_get_clean();
return $fragments;
}
It still does not work. The page only updates the cart if you refresh the whole page
you need to check the class of the cart.
ex. <a class="cart-contents
mine was wccart-contents
change the class to yours and it will work
Thanks man!
OK – thanks for the update – now one last request.
If someone goes to their cart and removes item(s) – the menu bar total does not refresh then either.
I’m assuming we’ll need to do another function file update/check to refresh after they change qty or delete line item(s)?
I’m seeing the same thing when removing an item, Matt.
Also, the icon disappears for me on mobile when my menu becomes the collapsable menu (hamburger). Anyone having that issue and a workaround?
I have the same issue with the cart menu item disappearing in the responsive menu. Haven’t found a fix so far.
Very good, it just reduced the plugin install on site. Could you tell me how to change the size of product images on product page.
Hi,
Thanks!, it works on my site.
Hi,
It doesn’t work for me. If I understand we must change “your-theme-slug” by something but I don’t understand what is this?
Can you explain me please? Sorry for my unfamiliarity (and my english).
Regards
your-theme-slug
does not matter (at least w.r.t functionality). It is for translation/localization.The same…
No error, clean console, clean code.
Nothing happened.
I don’t know why. Maybe isn’t working on Wordpres 1.6.1 ?
Ok, I know now.
I had to change my menu name to ‘primary’.
It was ‘header_menu’.
Thanks
Hi,
Great code!
I’ve got it working on my site, with ajax working (using the code provided above) when adding a product to the cart.
I have one issue left though.
When I change the number of products in my cart/shopping basket and I click Update Cart, my cart/shopping basket is updated but the cart icon in the menu isn’t.
Which code do I need to add to the functions.php of my child theme to get the menu cart icon updated anytime a client makes changes in his/her cart/shopping basket ?
Hi Sridhar Katakam,
thank you for nice piece of code. It works like a charm even now, 3 years after you first published it.
Now, is there a way to place that cart on top of menu? I am using left-sided menu and the code places the cart on the bottom of menu. I would like to move it up above the first item.
Could you advise on how to do that? I was looking for a solution for some time, but did not find anything.
Thank you very much
Did anyone figure out how to add ajax to the cart. The code mentioned above appears not to work i.e:
add_filter( ‘woocommerce_add_to_cart_fragments’, ‘woocommerce_header_add_to_cart_fragment’ );
function woocommerce_header_add_to_cart_fragment( $fragments ) {
ob_start();
?>
get_cart_url(); ?>” title=””>cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> – cart->get_cart_total(); ?>
<?php
$fragments['a.cart-contents'] = ob_get_clean();
return $fragments;
}
Appreciate an insight.
Has anyone solved the responsive menu issue?
Great work, thanks!!!
Hi thanks for this site!
I have setup an online menu using the WPPIZZA plugin (WordPress, 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.
Hi Sri – I’m having the issue that when an item is added to the cart it shows the count in the header but them if you leave the cart/product page it resets to zero. It’s still right if you go back to cart but it needs to stay when you browse the site. What is happening? A cache thing? thanks!
Works like a charm …. awesome. Thanks so much.
Please someone tell me the proper code to ajaxify upadate of cart contents and total
Works fine except if you empty cart from cart page, the cart in menu does not empty.
hey sridhar, this is great. is it possible to only show the cart if an item has been added? if nothing has been added, i’d like the icon to be hidden. thanks!
Did you uncomment the line where it says:
// Uncomment the line below to hide nav menu cart item when there are no items in the cart
then there’s also one near the bottom.
Thank you so much for posting this! Thank you thank you thank you!
Thank you! it helped me in last minutes!
Hello,
Can you help me out please
how can I manually put a woocommerce cart icon on a footer area of wordpress theme?
thanks in advance
Add ajax update of the cart menu when added to cart using ajax.
Hi. This is great! Thanks.
I was wondering if there is an update to the code. I’m getting an error notice that says this:
“Notice: WC_Cart::get_cart_url is deprecated since version 2.5! Use wc_get_cart_url instead.”
But, when I change get_cart_url to wc_get_cart_url I get about 5 more lines of error notices.
Thanks again!
Hello,
I’m getting also an error :
“Notice: WC_Cart::get_cart_url is deprecated since version 2.5! Use wc_get_cart_url instead.”
But, when I change get_cart_url to wc_get_cart_url I get about 5 more lines of error notices.
How can i fix this?
WC_Cart::get_cart_url or $woocommerce->cart->get_cart_url replace this in the functions.php with this wc_get_cart_url, that should fix it.
[…] I’m going to share the code extracted from the Woocommerce Menu Cart plugin here. It functions exactly like the plugin mentioned above. Simply add this code into your theme’s functions.php and you’re ready to go. For more customized options, take a look at this article. […]
Hey thanks for sharing. I was stuck on a similar issue and your post helped me for woocommerce. Keep posting.
Thanks for custom code.
Any ideas on how to make this work with caching for example, WP Rocketcache? Need Ajax?
Worked Perfectly! Thanks a lot man.
Looks brilliant. But we’re a few years later now. I can’t get it to work in WP 6 and WC 6.6.1.
Any suggestions?