Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Show WooCommerce basket total in wp_nav_menu item
<?php
/**
* A walker class for specific navigation menus in your theme, where you'd like to be
* able to show your WooCommerce basket total
*
* @package YOUR_THEME
* @since 1.0.0
*/
if (!class_exists('Theme_WC_Nav_Menu')) {
class Theme_WC_Nav_Menu extends Walker_Nav_Menu {
public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
parent::start_el($output, $item, $depth, $args, $id);
if (in_array('wc-basket-total', $item->classes) && function_exists('WC')) {
$output = str_replace('%n',
sprintf('<span class="total">%s</span>', WC()->cart->get_cart_contents_count()),
$output);
}
}
}
}
You'll need to create a copy of the class-theme-wc-walker.php file in
your theme, and then include it in your functions.php file.
For this to work, we're targetting a specific class on a menu item in your
menu. So on the item where you want to show the basket total, you'll need
to add a class of "wc-basket-total"
As well as that, you'll also need to add "%n" wherever you want the total
to show up in the string. Aside from that, there's not much else to do.
But here's an exampe, just in case:
My basket (%n)
..which, assuming the basket has 4 items in it, would render in your front-
end markup as:
My basket (<span class="total">4</span>)
Feel free to fork and change the code above.
<?php
wp_nav_menu([
'theme_location' => 'YOUR_MENU_NAME',
'walker' => new Theme_WC_Nav_Menu
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.