WordPressにて、プラグインを使わずに関連記事を表示させる方法をご紹介いたします。
「投稿に設定されているタグをベースに関連記事を取得する方法」と「投稿に設定されているタームをベースに関連記事を取得する方法」の2通りを紹介します。
プラグインなしで関連記事を表示させる方法
タグをベースに関連記事を取得・表示
single.phpなどのテーマファイル内で、以下を追加するだけです。投稿に設定されているタグをベースに関連記事を取得・表示します。
<?php
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo '<h3>関連記事</h3><ul class="relatedpost">';
$first_tag = $tags[0]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'showposts'=>5,
'orderby' => 'rand',
'ignore_sticky_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; } echo '</ul>';} ?>
showpostsの値を変更すれば、関連記事の表示数を調整できます。関連記事がリストで表示されますので、装飾はCSSで整えましょう。
サムネイルも表示させたい場合は、ループ内に以下を追加しましょう。
<?php the_post_thumbnail('thumbnail'); ?>
タクソノミーをベースに関連記事を取得・表示
投稿に設定されているタクソノミーのタームをベースに関連記事を取得するには、以下のように記述します。
<?php
$terms = get_the_terms($post->ID,'タクソノミー名');
foreach( $terms as $term ) {
$term_slug = $term->slug;
}
if ($term_slug) {
echo '<h3>関連記事</h3><ul class="relatedpost">';
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'showposts'=> 5,
'orderby' => 'rand',
'ignore_sticky_posts'=> 1,
'tax_query' => array(
array(
'taxonomy' => 'タクソノミー名',
'field' => 'slug',
'terms' => $term_slug
))
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; } echo '</ul>';} ?>
‘タクソノミー名’のところは、使用したいタクソノミー名を入れてください。例えば、カテゴリーをベースに関連記事を取得したい場合は’category’になります。
あとがき
上述したコードをほぼコピペで実装できますので、プラグインを使用したくない場合はぜひお試しください。
プラグインを使って関連記事を表示させる場合は、Yet Another Related Posts Pluginを使うと簡単です。

![[WordPress] プラグインなしで関連記事を表示させる方法 [WordPress] プラグインなしで関連記事を表示させる方法](https://techmemo.biz/wp-content/uploads/2017/01/relatedpost-noplugins.jpg)