Skip to content

Instantly share code, notes, and snippets.

@cklosowski
Created March 25, 2017 15:34
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save cklosowski/df41c06eb21f0405a618606f2b0daacc to your computer and use it in GitHub Desktop.
Here's a quick function that will look at the categories in the product list, find the products in the category, and if none of the products are visible, it will not display the category in the widget: https://chrisk.io/woocommerce-hide-categories-with-no-visible-products-in-the-product-category-widget/
<?php
/**
Plugin Name: WooCommerce - Exclude empty categories from widget
Plugin URI: https://chrisk.io/woocommerce-hide-categories-with-no-visible-products-in-the-product-category-widget/
Description: Excludes categories with no visible products from the WooCommerce category list
Version: 0.1
Author: Chris Klosowski
Author URI: https://chrisk.io
*/
/**
* Exclude categories with no visible products from the category list
*
* @param array $category_list_args Array of wp_list_categories parameters
* @return array Addition of exclude if items are not visible
*/
function kfg_exclude_categories_from_widget( $category_list_args ) {
$args = array(
'hide_empty' => false,
'hierarchical' => true,
);
$product_categories = get_terms( 'product_cat', $args );
$exclude = array();
foreach ( $product_categories as $category ) {
$posts = get_posts( array( 'post_type' => 'product', 'posts_per_page' => -1, 'product_cat' => $category->slug, 'fields' => 'ids' ) );
$show_category = false;
foreach ( $posts as $post ) {
$product = new wC_Product( $post );
$visible_product = $product->is_visible();
if ( true === $visible_product ) {
$show_category = true;
break;
}
}
if ( false === $show_category ) {
$exclude[] = $category->term_id;
}
}
if ( ! empty( $exclude ) ) {
$category_list_args['exclude'] = implode( ',', $exclude );
unset( $category_list_args['include'] );
}
return $category_list_args;
}
add_filter( 'woocommerce_product_categories_widget_args', 'kfg_exclude_categories_from_widget', 10, 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment