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

问题描述 投票:0回答:1

如何在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 . ')';
  }
wordpress woocommerce count categories product
1个回答
0
投票

将此代码粘贴到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');?>

© www.soinside.com 2019 - 2024. All rights reserved.