5

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.

4

2 回答 2

11

这两个函数get_termget_terms将返回已经包含类别计数的对象。

如果要检索所有WooCommerce 产品类别并打印其帖子数:

$terms = get_terms( 'product_cat' );
// DEBUG
// var_dump( $terms ); 
foreach( $terms as $term ) 
{
    echo 'Product Category: '
        . $term->name
        . ' - Count: '
        . $term->count;
}       

如果您只想检查一个您以前知道 ID 的类别:

$term = get_term( 16, 'product_cat' ); // <--- tested in my system with this ID
echo 'Product Category: '
    . $term->name
    . ' - Count: '
    . $term->count;
于 2013-07-13T02:47:46.477 回答
2

好的,谢谢你让我走上正确的轨道 brasofilo,我确信我有一些冗余,但这让我得到了我需要的东西。

<?php $cat1 = $product->get_categories( ', ', '<span class="posted_in">' . _n(       'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '</span>' ); 

//get the category ID and permalink
$term_list = wp_get_post_terms($post->ID,'product_cat',array('fields'=>'ids'));
$cat_id = (int)$term_list[0];
$term = get_term( $cat_id, 'product_cat' ); 

//echo the category, product count, and link
echo  $cat1 . '<a href='. get_term_link ($cat_id, 'product_cat') .'>' . ' See all ' .   $term->count . ' Activities</a>';


?>
于 2013-07-15T22:58:54.970 回答