【wordpress】関連記事を通常投稿とカスタム投稿で分けて表示させる方法

wordpressで現在表示している記事以外かつ、同じカテゴリーの記事を関連記事として表示させる際のコードを紹介します。

通常投稿の中だけで動作する関連記事のコードや、カスタム投稿タイプの中だけで動作するコードはありますが、両方合わせたものが見つからなかったので書いてみました。

関連記事を表示するコード

この記事の一番下にある関連記事の部分で実際に利用しているコードです。

<?php
$categories = get_the_category();
$taxonomies = get_object_taxonomies(get_post_type(), 'objects');

if ($categories || $taxonomies) {
    $related_args = array(
        'post_type' => array('post', 'column', 'powerautomate'),//変更する際はここを変えてください。
        'post_status' => 'publish',
        'posts_per_page' => 4,
        'post__not_in' => array(get_the_ID()),
        'orderby' => 'rand',
        'tax_query' => array(
            'relation' => 'OR'
        ),
    );

    foreach ($categories as $category) {
        $related_args['category_name'] = $category->slug;
    }

    foreach ($taxonomies as $taxonomy) {
        if ($taxonomy->name == 'category') {
            continue;
        }

        $terms = get_the_terms(get_the_ID(), $taxonomy->name);

        if (is_array($terms) && count($terms) > 0) {
            $term_slugs = array();
            foreach ($terms as $term) {
                $term_slugs[] = $term->slug;
            }

            $related_args['tax_query'][] = array(
                'taxonomy' => $taxonomy->name,
                'field' => 'slug',
                'terms' => $term_slugs
            );
        }
    }

    $related_query = new WP_Query($related_args);
    if ($related_query->have_posts()) :
?>
        <div class="related-articles">
            <h3>Related Articles</h3>
            <ul>
                <?php while ($related_query->have_posts()) : $related_query->the_post(); ?>
                    <li>
                          <a href="<?php the_permalink() ?>">
                                <?php if (has_post_thumbnail()) : ?>
                                    <?php the_post_thumbnail(); ?>
                                <?php else : ?>
                                    <img src="/images/noimage.png" />
                                <?php endif; ?>
                                <div><?php the_title(); ?></div>
                          </a>
                    </li>
                <?php endwhile; ?>
            </ul>
        </div>
<?php
    endif;
    wp_reset_postdata();
}
?>

解説

$categories = get_the_category();
$taxonomies = get_object_taxonomies(get_post_type(), 'objects');

まず、get_the_category()とget_object_taxonomies()という関数を使って、現在の投稿が属するカテゴリーとタクソノミー(カスタム分類)を取得します。


 $related_args = array(
        'post_type' => array('post', 'column', 'powerautomate'),//変更する際はここを変えてください。
        'post_status' => 'publish',
        'posts_per_page' => 4,
        'post__not_in' => array(get_the_ID()),
        'orderby' => 'rand',
        'tax_query' => array(
            'relation' => 'OR'
        ),
    );

次に、$related_argsという配列を作って、関連記事のクエリ条件を設定します。

このサイトでは、

  • 投稿タイプ:投稿(post)、カスタム投稿2つ(column, powerautomate)
  • 投稿ステータス(公開)
  • 表示件数(4)
  • 除外する投稿ID(現在の投稿)
  • 並び順(ランダム)
  • タクソノミークエリ(OR)

を指定しています。


    foreach ($categories as $category) {
        $related_args['category_name'] = $category->slug;
    }

    foreach ($taxonomies as $taxonomy) {
        if ($taxonomy->name == 'category') {
            continue;
        }

        $terms = get_the_terms(get_the_ID(), $taxonomy->name);

        if (is_array($terms) && count($terms) > 0) {
            $term_slugs = array();
            foreach ($terms as $term) {
                $term_slugs[] = $term->slug;
            }

            $related_args['tax_query'][] = array(
                'taxonomy' => $taxonomy->name,
                'field' => 'slug',
                'terms' => $term_slugs
            );
        }
    }

foreach文でカテゴリーとタクソノミーをループして、それぞれのスラッグ名を$related_argsに追加していきます。

これにより、現在の投稿と同じカテゴリーやタクソノミーに属する記事が検索対象になります。

まとめ

以上wordpressで関連記事を表示させるphpのコードでした。

関連記事関係はよく使っている気がするので自分の忘備録としておいておきます。