Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.