LoginSignup
3
2

More than 5 years have passed since last update.

WordPressで記事のカテゴリーごとに投稿を表示する

Last updated at Posted at 2019-05-13

前置き

最近話題のWordPressですが何故か自分も触れる機会が増えてきたので備忘録として

環境

  • macOS Mojave
  • Docker for Mac
  • WordPress 5.2
  • PHP7.3

表示したい内容

Hogeカテゴリーの投稿一覧
・Hoge1
・Hoge2
・Hoge3
Fugaカテゴリーの投稿一覧
・Fuga1
・Fuga2
・Fuga3

コード

適当なテンプレートに以下のコードを記述してテンプレートを適用する。

<?php 
$categories = get_categories();
foreach ($categories as $category) {
    $wpb_all_query = new WP_Query(
      array(
        'cat' => $category->cat_ID,
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => -1)
    );
    ?>
    <section class="xxx">
      <div class="yyy">
        <?php echo $category->cat_name; ?>カテゴリーの投稿一覧
    	<?php while ($wpb_all_query->have_posts()): $wpb_all_query->the_post();?>
        <li><a href="<?php the_permalink();?>"><?php the_title();?></a></li>
	    <?php endwhile;?>
	  </div>
	</section>
<?php } ?>

その他

WordPressだとarrayを省略して書かないことが多いのは何故...?

3
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2