Last active
March 20, 2024 17:06
-
-
Save michaelbourne/18990cbd781b92a709a8866f38f464ee to your computer and use it in GitHub Desktop.
Create a simple shortcode to output the Woocommerce cart count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ''; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.)