在带有子类别的WooCommerce类别中显示产品计数



如何在WooCommerce中显示带有子类别的类别中的产品总数? 我正在尝试使用此代码,但它仅在没有子类别的类别中完美运行。

add_action( 'woocommerce_before_shop_loop', 'add_product_count_view', 10);
function add_product_count_view() {
global $wp_query;
$category_id = $wp_query->get_queried_object()->term_id;
$term = get_term( $category_id, 'product_cat' );  
echo $term->name . '(' . $term->count . ')';
}

将此代码粘贴到 function.php:

add_action( 'count_product_title', 'add_product_count_view', 10);
function add_product_count_view() {
global $wp_query;
$category_id = $wp_query->get_queried_object()->term_id;
//echo sprintf( _n( '%d товар', '%d товаров', $term->count ), $term->count );
$query = new WP_Query( array(
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $category_id, 
'include_children' => true,
),
),
'nopaging' => true,
'fields' => 'ids',
) );
if( function_exists("is_shop") && $category_id != 0) {
echo '(' .esc_html( $query->post_count ) . ')';
}
}

粘贴到模板中<?php do_action('count_product_title');?>

最新更新