Add a Cart Item to the Main Menu
Appends a cart link with the item count to your theme's primary menu, and keeps the count up to date as products are added.
Opens WPIDE on
Code
$wpide_cart_menu_location = 'primary'; // Theme menu location.
$wpide_cart_menu_link = function () {
$count = WC()->cart ? WC()->cart->get_cart_contents_count() : 0;
return sprintf( '<a class="wpide-menu-cart" href="%1$s">Cart (%2$d)</a>', esc_url( wc_get_cart_url() ), (int) $count );
};
add_filter( 'wp_nav_menu_items', function ( $items, $args ) use ( $wpide_cart_menu_location, $wpide_cart_menu_link ) {
if ( isset( $args->theme_location ) && $args->theme_location === $wpide_cart_menu_location ) {
$items .= '<li class="menu-item wpide-menu-cart-item">' . $wpide_cart_menu_link() . '</li>';
}
return $items;
}, 10, 2 );
add_filter( 'woocommerce_add_to_cart_fragments', function ( $fragments ) use ( $wpide_cart_menu_link ) {
$fragments['a.wpide-menu-cart'] = $wpide_cart_menu_link();
return $fragments;
} );
Notes
Set $location to your theme's menu location slug (look under Appearance > Menus > Manage Locations). Works with classic menus.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.