最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Display category filters for custom post type when category is shared by multiple post types

programmeradmin1浏览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.

发布评论

评论列表(0)

  1. 暂无评论