Last active
September 19, 2017 11:06
-
-
Save Vyygir/a4b9b107630b312726c5b75e049c0b34 to your computer and use it in GitHub Desktop.
Show WooCommerce basket total in wp_nav_menu item
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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