今表示している記事と同じカテゴリ、タグの記事一覧を取得する

今見ているページに関連する記事を用意することで、訪問者の求める情報を多く持つページとなりサイト内回遊率をあげることができます。
WordPressでは関連記事の取得は簡単です。
今回はWordPressで今表示している記事と同じカテゴリ、タグを持つ記事を取得する方法を紹介します。
今見ている記事の持つカテゴリ、タグを取得
記事の持つ情報を取得する方法をおさらいします。
記事の持つカテゴリ、タグはそれぞれ以下の関数を使うことで取得できます。
| get_the_category() | 記事ループ内で呼び出すとその記事が持つカテゴリの一覧が取得できます。 |
|---|---|
| get_the_tags() | 上の関数と同様に、その記事が持つタグの一覧が取得できます。 |
<?php // 表示している記事のカテゴリ、タグを取得 $categories = get_the_category(); $tags = get_the_tags(); ?>
取得したカテゴリを持つ記事を取得
記事ループの条件に get_the_category() で取得したカテゴリIDを渡します。
パラメーター category__in を使用することで、複数のカテゴリを渡した場合いずれかを含む記事を取得できます。
<?php
// 表示している記事のカテゴリを取得
$categories = get_the_category();
$cat_id = [];
// 表示している記事の持つカテゴリーを持つ記事を取得
if ( !empty($categories) ):
foreach ( $categories as $cat ):
$cat_id[] = $cat->term_id;
endforeach;
$args = ['category__in' => $cat_id];
endif;
// 条件を渡して記事を取得
if ( !empty($args) ): ?>
<ul>
<?php
$custom_posts = new WP_Query($args);
while ( $custom_posts->have_posts() ) : $custom_posts->the_post(); ?>
<li><?php the_time('Y/m/d') ?> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
endwhile;
?>
</ul>
<?php endif; ?>
取得したタグを持つ記事を取得
タグの場合もカテゴリ同様に取得できます。
<?php
// 表示している記事のタグを取得
$tags = get_the_tags();
$tag_id = [];
// 表示している記事の持つタグを持つ記事を取得
if ( !empty($tags) ):
foreach ( $tags as $tag ):
$tag_id[] = $tag->term_id;
endforeach;
$args = ['tag__in' => $tag_id];
endif;
// 条件を渡して記事を取得
if ( !empty($args) ): ?>
<ul>
<?php
$custom_posts = new WP_Query($args);
while ( $custom_posts->have_posts() ) : $custom_posts->the_post(); ?>
<li><?php the_time('Y/m/d') ?> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
endwhile;
?>
</ul>
<?php endif; ?>
関連記事







