# Cart Link With Item Count Shortcode

> Adds a [wpide_cart_link] shortcode that shows a cart link with the number of items and total, which updates automatically when products are added.

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

## Code

```php
$wpide_cart_link_html = function () {
    if ( ! WC()->cart ) {
        return '<a class="wpide-cart-link" href="' . esc_url( wc_get_cart_url() ) . '">Cart</a>';
    }

    $count = WC()->cart->get_cart_contents_count();

    return sprintf(
        '<a class="wpide-cart-link" href="%1$s">Cart <span class="wpide-cart-count">(%2$d)</span> %3$s</a>',
        esc_url( wc_get_cart_url() ),
        (int) $count,
        $count ? wp_kses_post( WC()->cart->get_cart_subtotal() ) : ''
    );
};

add_shortcode( 'wpide_cart_link', function () use ( $wpide_cart_link_html ) {
    return $wpide_cart_link_html();
} );

add_filter( 'woocommerce_add_to_cart_fragments', function ( $fragments ) use ( $wpide_cart_link_html ) {
    $fragments['a.wpide-cart-link'] = $wpide_cart_link_html();

    return $fragments;
} );

add_action( 'wp_enqueue_scripts', function () {
    if ( function_exists( 'is_woocommerce' ) && wp_script_is( 'wc-cart-fragments', 'registered' ) ) {
        wp_enqueue_script( 'wc-cart-fragments' );
    }
} );
```

## Notes

Place it in a header widget, Shortcode block or menu. Uses WooCommerce cart fragments to refresh.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Cart Link With Item Count Shortcode" 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/
