Skip to content

Instantly share code, notes, and snippets.

@michaelbourne
Last active March 20, 2024 17:06
Show Gist options
  • Save michaelbourne/18990cbd781b92a709a8866f38f464ee to your computer and use it in GitHub Desktop.
Save michaelbourne/18990cbd781b92a709a8866f38f464ee to your computer and use it in GitHub Desktop.
Create a simple shortcode to output the Woocommerce cart count
<?php
// Add cart count shortcode [cart_count]
// =============================================================================
add_shortcode( 'cart_count', 'mb_cart_count' );
function mb_cart_count() {
if ( class_exists( 'WooCommerce' ) && function_exists( 'WC' ) ) { // Check for WooCommerce and WC() function.
if ( ! WC()->cart->is_empty() ) {
return (string) WC()->cart->get_cart_contents_count(); // Cast to string for consistency.
}
return '0';
}
return '';
}
@michaelbourne
Copy link
Author

@KZeni Good call, you found an old one here :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment