WordPressでカテゴリとタグを表示する

2023.11.21 09:00
2023.11.20 14:34
WordPressでカテゴリとタグを表示する

今回はWordPressでカテゴリとタグを表示してみたいと思います。
「templates」フォルダの中にパーツとして切り出します。「content-category.php」と「content-tag.php」を作りそれぞれ処理を書いてみます。

<?php if(!empty($args)):?>
  <h3>カテゴリ別の記事</h3>
  <ul>
    <?php if(count($args) > 0):?>
    <?php foreach($args as $category):?>
    <?php if($category->count > 0):?>
    <li class="c-article__otherList">
      <a href="<?php echo $category->id;?>"><?php echo $category->name;?>(<?php echo $category->count;?>件)</a>
    </li>
    <?php endif;?>
    <?php endforeach;?>
    <?php endif;?>
  </ul>
<?php endif;?>

content-category.php

<?php if(!empty($args)):?>
  <h3>タグ別の記事</h3>
  <ul>
    <?php if(count($args) > 0):?>
    <?php foreach($args as $tag):?>
    <?php if($tag->count > 0):?>
    <li class="c-article__otherList">
      <a href="<?php echo $tag->id;?>"><?php echo $tag->name;?>(<?php echo $tag->count;?>件)</a>
    </li>
    <?php endif;?>
    <?php endforeach;?>
    <?php endif;?>
  </ul>
<?php endif;?>

content-tag.php

呼び出し側はこんな感じです。

      <?php 
      // カテゴリ取得
      $categories = get_categories();

      // カテゴリ表示
      get_template_part('templates/content-category', null , $categories);

      // タグ取得
      $tags = get_tags();

      // タグ表示
      get_template_part('templates/content-tag', null , $tags);?>

これでそれぞれが無事表示されます。
また、記事がないカテゴリやタグは表示されないようになっています。

今回は以上です!