简体   繁体   中英

How to check if a certain product category is empty in WooCommerce?

I need to check if a certain product category is empty in WooCommerce. I already know how to check if it's a certain category by using the code below, but I don't know how to check if there are any products assigned to that category.

if ( is_product_category( 'name-of-category') { echo 'An example message'; }

There may be a native WooCommerce function for this, but this will get you the result you need.

The first part just gets the count of items in the current category. Then, the if sorts as to whether there are more than 0 items in that category while making sure we're on a product_category page.

    $category = get_queried_object();
    $theCount = $category->count;

    if ( ( is_product_category( 'my-product-category-slug' ) ) && ( $theCount > 0 ) ){

        echo 'Total: ' . $theCount . ' products in this category';

    } else {

        echo 'There are no products in this category';

    }

functions.php

add_filter('woocommerce_product_subcategories_args', 'woocommerce_show_empty_categories');
function woocommerce_show_empty_categories($cat_args){
$cat_args['hide_empty']=0;
return $cat_args;
}

I hope this helps you will need to add this in your functions.php

This should do it:

<?php if (get_category('1')->category_count <= 0) echo "message"; ?>

In this example the category ID is 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM