0

I am creating a dropdown of categories using get_categories() and I am using the hide_empty attribute to exclude categories which have no posts assigned to them. This is working pretty well, except I have another condition. I have various categories which I want to exclude from the post query depending on various conditions. These categories are still showing up in the dropdown because even though the query does not return any posts from the categories, they are still not considered "empty" since there are posts assigned to them. Is it possible for the hide_empty attribute to honor categories which have posts but those posts are being excluded from the query?

5
  • Have you tried the exclude parameter? get_categories( [ 'exclude' => [ 1, 2, 3 ] ] )
    – Sally CJ
    Mar 11, 2020 at 16:24
  • @SallyCJ unfortunately that won't work because the categories need to be excluded dynamically and the posts are assigned to multiple categories. For one condition I may need to exclude category 3, but for another condition I may need to exclude category 4, it changes depending on various conditions so I cannot hardcode the excluded categories.
    – user13286
    Mar 11, 2020 at 16:29
  • This question helped me get it working: stackoverflow.com/a/32147547/2827407 basically instead of just relying on get_categories by itself, I use that to get a list of all categories and then I loop over those and generate a WP_Query for each category and pass my conditional category exclusions into those queries and then display the category in the dropdown if found_posts > 0.
    – user13286
    Mar 11, 2020 at 17:31
  • It sounds like you’re using categories for two different purposes. It would probably save you a lot of trouble if you mean these other categories a separate taxonomy entirely. Mar 12, 2020 at 0:35
  • I'm creating a dropdown in order to allow the user to filter the blog posts by category. Some of the posts will not be available to certain users though depending on their geography ,so I just wanted to hide categories in the dropdown that contain posts but none that should be available for the user to view.
    – user13286
    Mar 12, 2020 at 2:07

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.