WordPressで特定のカテゴリを一覧表示する方法

WordPressのイメージ

特定カテゴリを一覧で表示

WordPressで特定の記事を一覧で表示する方法についてご紹介します。

1つのカテゴリを一覧で取得する場合

オプションはcategoryを記述し、categoryのidを1つ指定して記述します。

<ul>
    <?php
        $args = array (
        'category' => 1, // カテゴリのIDを記入する
        'order' => 'DESC', // 記事の並び順 昇順(ASC)、降順(DESC)
        'paged' => $paged,
        'post_per_page' => 10, //表示する記事の数
    );
    $paged = (int) get_query_var('paged');
    $the_query = new WP_Query( $args ); ?>
    <?php if( $the_query -> have_posts() ): while ( $the_query -> have_posts()): $the_query -> the_post(); ?>
    <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
    <?php endwhile; endif; ?>
</ul>

こちらは表示したいカテゴリーのスラッグを指定するパターンです。
オプションはcategory__nameを記述し、categoryのスラッグを1つ指定して記述します。

<ul>
    <?php
        $args = array (
        'category__name' => 'category_1', // カテゴリのスラッグを1つ指定する
        'order' => 'DESC', // 記事の並び順 昇順(ASC)、降順(DESC)
        'paged' => $paged,
        'post_per_page' => 10, //表示する記事の数
    );
    $paged = (int) get_query_var('paged');
    $the_query = new WP_Query( $args ); ?>
    <?php if( $the_query -> have_posts() ): while ( $the_query -> have_posts()): $the_query -> the_post(); ?>
    <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
    <?php endwhile; endif; ?>
</ul>

複数のカテゴリを一覧で取得する場合

オプションはcategory__inを記述し、categoryのidを複数指定して記述します。

<ul>
    <?php
        $args = array (
        'category__in' => array(1, 2, 3, 4), // カテゴリのIDを複数記入する
        'order' => 'DESC', // 記事の並び順 昇順(ASC)、降順(DESC)
        'paged' => $paged,
        'post_per_page' => 10, //表示する記事の数
    );
    $paged = (int) get_query_var('paged');
    $the_query = new WP_Query( $args ); ?>
    <?php if( $the_query -> have_posts() ): while ( $the_query -> have_posts()): $the_query -> the_post(); ?>
    <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
    <?php endwhile; endif; ?>
</ul>

こちらもカテゴリーのスラッグを指定するパターンです。
オプションはcategory__nameを記述し、categoryのスラッグを複数指定して記述します。

<ul>
    <?php
        $args = array (
        'category__name' => 'category_1, category_2', // カテゴリのnameを複数カンマ区切りで記入する
        'order' => 'DESC', // 記事の並び順 昇順(ASC)、降順(DESC)
        'paged' => $paged,
        'post_per_page' => 10, //表示する記事の数
    );
    $paged = (int) get_query_var('paged');
    $the_query = new WP_Query( $args ); ?>
    <?php if( $the_query -> have_posts() ): while ( $the_query -> have_posts()): $the_query -> the_post(); ?>
    <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
    <?php endwhile; endif; ?>
</ul>

参考記事
PHP - WP_Queryで複数のカテゴリーとカスタムフィールドで条件を設定したい|teratail
複数の違うカテゴリの記事をまとめて取得し一覧に表示するコード