# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [WooCommerce](https://wpide.com/library/category/woocommerce/)
- Requires: WooCommerce
- Tags: woocommerce, cart, menu, header
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/woo-cart-menu-item/

## Code

```php
$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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Add a Cart Item to the Main Menu" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
