Skip to content

Instantly share code, notes, and snippets.

@BluePraise
Last active September 13, 2020 20:49
Show Gist options
  • Save BluePraise/69a8ce0444426d80afcf0949bd72f6b7 to your computer and use it in GitHub Desktop.
Save BluePraise/69a8ce0444426d80afcf0949bd72f6b7 to your computer and use it in GitHub Desktop.
Show total number of items from WooCommerce Shopping Cart in a custom badge or mini cart
// Put this code in your (child) theme:
/*
* Mini cart with total count of items.
* This does not add the total amount of price.
* Do not put the hide on it by default, because that won't work.
* Leave it in the else statement.
*/
add_filter( 'woocommerce_add_to_cart_fragments', 'add_to_cart_fragment', 10, 1 );
function add_to_cart_fragment( $fragments ) {
global $woocommerce;
$count = $woocommerce->cart->cart_contents_count;
if ($count > 0) {
$fragments['.cart-counter'] = '<span class="cart-counter">' . $count . '</span>';
}
else {
// hide the badge when there are 0
$fragments['.cart-counter'] = '<span class="cart-counter hide">' . $count . '</span>';
}
return $fragments;
}
// Only get the number of the items without a word postfixed.
// Show number in badge.
<a class="btn shopping-cart" href="<?php echo wc_get_cart_url(); ?>" role="button">
<span>cart </span>
<span class="cart-counter"></span>
</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment