0

I'm using the following code and the Widget Logic plugin to dynamically display or hide a widget on category pages:

$thiscat = get_category( get_query_var( 'cat' ) );
$parent = $thiscat->category_parent;
return
!(is_page( ) || (is_category( ) && empty ($parent) ) );

I would like to add a further condition to this that checks whether or not the current category has any posts assigned to it. If not, then don't display the widget.

I tried using category_count;. but couldn't get it to work. Here's the complete code I tried:

$thiscat = get_category( get_query_var( 'cat' ) );
$parent = $thiscat->category_parent;
$postcount = $thiscat->category_count;
return
!(is_page( ) || (is_category( ) && empty ($parent) && $postcount > 0 ) );
2

It might be you're using the category on a custom post type, in that case category_count won't include those. There's another handy value on the $category-object however: $category->count. Try replacing this:

$postcount = $thiscat->category_count;

with this

$postcount = $thiscat->count;

The count attribute includes custom post types as well if the custom post type uses standard categories.1

  • Thanks, I tried that but still can't get it to work. I think it might be a problem with the syntax. – jrcollins Nov 24 '16 at 20:45
  • This is what I tried: $thiscat = get_category( get_query_var( 'cat' ) ); $parent = $thiscat->category_parent; $postcount = $thiscat->count; return !(is_page( ) || (is_category( ) && empty ($parent) && $postcount > 0 ) ); – jrcollins Nov 24 '16 at 20:47
  • It turns out I don't need !is_page() as the widget is for displaying posts and I'm not even sure why I had that in the code. I also decided I don't need empty ($parent) either as the parent categories don't have any posts assigned to them. So, this is what I'm left with: $thiscat = get_category( get_query_var( 'cat' ) ); $postcount = $thiscat->count; return $postcount > 0; – jrcollins Nov 25 '16 at 9:15
  • @jrcollins Nice, glad it worked out! :) – Emil Nov 25 '16 at 10:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.