I am trying to display the Woocommerce cart count by product category.
- I have two categories: "protein" and "pantry"
- I want to display the count by item category. So if there are 2 protein and 4 pantry, I want those two item category counts to be displayed next to each other, updating with ajax.
- e.g. the final look would say: PROTEIN 2 in cart and PANTRY 4 in cart (depending on the amount of item types in the cart)
I have found this snippet here which displays the cart count for a given category, but I am having trouble displaying it on the web page correctly. Currently It just displays the total amount of items in the cart:
function cat_cart_count( $cat_name ) {
global $woocommerce; $cat_count = 0;
// For each product in the cart
foreach(WC()->cart->get_cart() as $cart_item_key => $values) {
$_product_id = $values['product_id']; // product ID
$_product_qty = $values['quantity']; // product quantity
// Getting categories of the product (could be more than one)
$terms = get_the_terms( $_product_id, 'product_cat' );
// Checking this product has a category
if ( $terms && ! is_wp_error( $terms ) ) {
$term_name = array();
// For each category of that product
foreach($terms as $term) {
// Adding the category name to an array
$term_name[] = $term->name;
// if the product has $cat_name category
if ( in_array( $cat_name, $term_name ) ) {
// add 1 x product quantity to the count
$cat_count =+ 1 * $_product_qty;
}
}
}
}
// Returning category count
if ( $cat_count != 0 ) {
return $cat_count;
} else {
return '';
}
}
I am trying to just display the counters as HTML so that I can embed on the page anywhere and customise from there:
<a class="cart-contents" href="<?php echo WC()->cart->get_cart_contents_count(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf (_n( '%d protein', '%d protein', cat_cart_count( "protein" ) ), cat_cart_count( "protein" ) ); ?> - <?php echo sprintf (_n( '%d pantry', '%d pantry', cat_cart_count( "pantry" ) ), cat_cart_count( "pantry" ) ); ?> - <?php echo WC()->cart->get_cart_contents_count(); ?></a>
Thanks in advance!
So we will need to:
I have also revisited, simplified and compacted your function
cat_cart_count()
.The complete code:
Code goes in function.php file of your active child theme (or active theme).Tested and works.
USAGE
1) To place the counter in the html code of a php file you will use:
2) To use the counter inside any php code you will call the function
**display_cart_counters()**
.