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.
Opens WPIDE on
Code
$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 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.