如何在WooCommerce后端等每个类别中获取产品数量?

Eth*_*ton 4 php wordpress woocommerce

我正在建立一个新网站,我对Woocommerce很满意.我只需要一个快速的技巧来获得每个类别的产品数量.我已经在每个产品上调出类别,但无法弄清楚如何从该类别中获取产品数量.

我有一个列表样式用于我的产品(实际上是活动网站的活动).看看图片.

我只想回应一下该类别旁边的"活动".这就是我获取我的类别的方式:

echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' );
Run Code Online (Sandbox Code Playgroud)

我试图通过使用以下方式获得计数:

$numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish'");
echo $numposts;
Run Code Online (Sandbox Code Playgroud)

但它回应了一些奇怪的数字.我尝试了该查询的一些变体,呼唤产品等.

[更新]

这就是我能做到的:

<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>
Run Code Online (Sandbox Code Playgroud)

但它实际上以"1"的增量计算所有类别中的所有产品....所以不是回应"类别:abc有"3"产品"它回应"类别:abc has"1 1 1 1 1 1 1 "

我知道我可以在这里做一个简单的过滤器,我觉得我就在那里.

bra*_*ilo 8

这两个函数get_term,并get_terms返回已经包含类别计数对象.

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

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

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

$term = get_term( 16, 'product_cat' ); // <--- tested in my system with this ID
echo 'Product Category: '
    . $term->name
    . ' - Count: '
    . $term->count;
Run Code Online (Sandbox Code Playgroud)


Eth*_*ton 4

好的,谢谢你让我走上正确的轨道,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>';


?>
Run Code Online (Sandbox Code Playgroud)