I am building a new site and I am pretty comfortable with Woocommerce. I just need a quick trick to get the product count in each category. I'm already calling out the category on each product but cannot figure out how to get the product count from that category.
I have a list style going for my products(really activities for an activity site). Check out image.
I just want to echo out the count of "activities" next to the category. This is how I am getting my category:
echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' );
I tried to get the count by using:
$numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish'");
echo $numposts;
But it is echoing out some weird number. I tried a few variations of that query, calling out for product and such.
[update]
This is what I was able to do:
<li><?php
$cat1 = $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' );
echo $cat1;
/*
$args = array( 'taxonomy' => 'product_cat' );
$terms = get_terms('product_cat', $args);
echo count($terms);
*/
$args = array( 'post_type' => 'product', 'taxonomy' => $cat1[0] );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo count( $loop->post->ID )
endwhile;
wp_reset_query(); // Remember to reset
?></li>
But it actually counts out all the products in all categories by increments of "1".... So instead of echoing "category: abc has "3" product" it's echoing "category: abc has "1 1 1 1 1 1 1"
I know there is a simple filter that I can do here, I feel like I am right there.
<?php
and close?>
tags to separate PHP from HTML. It is not a line break. 2) Organize your code, so you don't go mad. It's much easier to debug and read. See coding standards. 3) Usevar_dump
andprint_r
to inspect your variables. – brasofilo