categories - Conditional that checks if a current category has any subcategory with posts

admin2025-01-07  3

I'm looking for a way to make a conditional rule that checks, in a category archive template, if the current category has any subcategories with posts.

More specifically, the posts are "products" in a Woocommerce setup.

So far I was only able to check if the current category has subcategories with the code below. But even after some searching I wasn't able to advance any further.

$term = get_queried_object();

$children = get_terms( $term->taxonomy, array(
'parent'    => $term->term_id,
'hide_empty' => false
) );
if($children) {
    echo 'something';
}

I'm looking for a way to make a conditional rule that checks, in a category archive template, if the current category has any subcategories with posts.

More specifically, the posts are "products" in a Woocommerce setup.

So far I was only able to check if the current category has subcategories with the code below. But even after some searching I wasn't able to advance any further.

$term = get_queried_object();

$children = get_terms( $term->taxonomy, array(
'parent'    => $term->term_id,
'hide_empty' => false
) );
if($children) {
    echo 'something';
}
Share Improve this question asked Feb 17, 2017 at 10:58 TiagoTiago 233 bronze badges 3
  • what is left is to check if those categories have posts right? – David Lee Commented Feb 18, 2017 at 2:12
  • @DavidLee Yes! Although I don't know if it's possible with this piece of code. – Tiago Commented Feb 20, 2017 at 9:59
  • Please check this... wordpress.stackexchange.com/questions/176317/… – Wajid Ali Commented Aug 7, 2021 at 6:12
Add a comment  | 

1 Answer 1

Reset to default 0

Please set hide_empty to true which will fetch only categories which is assigned to post.

$term = get_queried_object();

$children = get_terms( 'category', array(
'parent' => $term->term_id,
'hide_empty' => true
) );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736254559a216.html

最新回复(0)