/woocommerce-hide-empty-categores.php
Forked from cklosowski/woocommerce-hide-empty-categores.php
Created Dec 30, 2020
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 ); | |
add_filter( 'woocommerce_product_categories_widget_dropdown_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
This comment has been minimized.
Added filter line for dropdown version of the product category widget.