0

I already have a solution to this problem but I'm wondering if there's a more efficient way to do it. I have a custom post type called "galleries" that uses the same taxonomy as blog posts. So if a user creates a category named "Animals" when making a blog post, that category will show up as an option when creating a new gallery.

On the gallery display page, I want to output a list of categories in a select element which are used to filter the galleries. However, if no galleries are using the category "Animals", that category shouldn't be displayed, since selecting it will return no results.

Here's how I solved this so far:

<?php
  // 1. Get all the categories
  $categories = get_categories( array(
     'orderby'   => 'name',
     'order'     => 'ASC'
  ) );
?>

<select>

<?php
// 2. Loop through the categories
foreach($categories as $cat) {

  // 3. Get the ID of the current category
  $category_id= get_cat_id($cat->name);

  // 4. Query the galleries post type for posts using the current category
  $args = array(
    'post_type' => 'galleries',
    'category' => $category_id
   );
  $posts = get_posts($args);

   // 5. Count the number of posts using the current category
   $count = count($posts);

   // 6. Display the option if that number is greater than 0
   if($count > 0) { ?>

     <option value="<?php echo $cat->slug; ?>"><?php echo $cat->name; ?></option>

   <?php } ?>

</select>

It seems like that's a lot of steps and maybe I'm doing this in a roundabout kind of way. Is there a more efficient way to do this? Thanks in advance.

2
  • I think your approach is already the best for now. But you don't need to call get_cat_ID() because you could just use $cat->term_id. Secondly, you should add 'posts_per_page' => 1 to the $args array because you're just checking whether the category has a post in the given post type. And you would also add 'suppress_filters' => false to allow plugins and custom code to filter the query - because the results could be different, yet the expected ones than without the filters applied.
    – Sally CJ
    Commented Oct 23, 2020 at 16:29
  • 1
    That removes one of the steps and makes it a little more robust, thank you!
    – Jake1293
    Commented Oct 23, 2020 at 20:02

0

Your Answer

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