【问题标题】:How can I get product count in each category like WooCommerce back-end?如何获得每个类别中的产品数量,例如 WooCommerce 后端?
【发布时间】:2013-07-09 22:40:12
【问题描述】:

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

我的产品有一个列表样式(活动网站的真正活动)。 Check out image.

我只想在类别旁边显示“活动”的计数。这就是我获得类别的方式:

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

我尝试使用以下方法获取计数:

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

但它正在呼应一些奇怪的数字。我尝试了该查询的一些变体,调用产品等。

[更新]

这是我能够做到的:

<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>

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

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

【问题讨论】:

  • 观察:1) 仅使用打开&lt;?php并关闭?&gt;标签将PHP与HTML分开。这不是换行符。 2)组织你的代码,这样你就不会发疯。它更容易调试和阅读。见coding standards。 3) 使用var_dumpprint_r 检查你的变量。

标签: php wordpress woocommerce


【解决方案1】:

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;

【讨论】:

    【解决方案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>';
    
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      • 2016-11-06
      • 2016-12-20
      • 1970-01-01
      • 2021-09-13
      • 2013-04-05
      • 2019-08-29
      相关资源
      最近更新 更多