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 '';
}
@KZeni
Copy link

KZeni commented Mar 20, 2024

Might be good to have something like if ( class_exists( 'woocommerce' ) ) { } around this shortcode's code to have it gracefully fail if/when WooCommerce is ever deactivated on the site rather than having it result in a 500 server error due to trying to call a function that's then not available to use (the official documentation at https://woo.com/document/query-whether-woocommerce-is-activated/ shows something similar while creating that full function seemed overkill as we can just check for that class directly here.)

@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