Mr. Jo
Mr. Jo

Reputation: 5261

WooCommerce wrong category count

I've included a function to show the product count in on the category overview page in WooCommerce:

add_action( 'woocommerce_before_subcategory_title', 'custom_woocommerce_subcategory_thumbnail', 10 );
function custom_woocommerce_subcategory_thumbnail( $category ) {
    echo $category->count;
}

The problem is that I've for example 4 products in category a, but one of them is hidden in the catalog. So there should be a changed category count of 3 because the 4th one is hidden. But there is stillt 4 shown.

How can I exclude hidden products from the count?

Upvotes: 1

Views: 969

Answers (1)

Noah
Noah

Reputation: 570

You will have to use a custom WP_Query that will only return visible items. Something like this:

add_action( 'woocommerce_before_subcategory_title', 'custom_woocommerce_subcategory_thumbnail', 10 );
function custom_woocommerce_subcategory_thumbnail( $category ) {
  $args = array(
    'posts_per_page' => -1, 
    'post_type' => 'product', 
    'product_cat' => $category->term_id,
    'meta_query' => array(
       array(
         'key'       => '_visibility',
         'value'     => 'hidden',
         'compare'   => '!=',
      )
    )
  );
  $wc_query = new WP_Query($args);

  echo $wc_query->found_posts;
}

Upvotes: 1

Related Questions