【WordPress】自作で関連記事を実装する方法【プラグインなし】

WordPressの投稿に関連記事を表示したい。
プラグイン無しの自作で実装したい。
本記事ではこのような悩みを解決。
実装方法について解説します。
関連記事を表示するコードサンプル
<?php
$cats = get_the_category();
// 現在のページカテゴリIDを取得
$category = array();
foreach ($cats as $cat) {
$category[] = $cat->cat_ID;
}
$args = array(
'post_type' => 'post', //投稿タイプ
'posts_per_page' => '4', //表示する記事数
'post__not_in' => array($post->ID), //現在記事は含めない
'category__in' => $category, //現在のページカテゴリID
'orderby' => 'rand' //ランダム取得
);
$the_query = new WP_Query($args);
?>
<?php if ($the_query->have_posts()) : ?>
<?php while ($the_query->have_posts()) : $the_query->the_post();
?>
<!-- ループで出す記事内容を入れる -->
<a class="list" href="<?php the_permalink(); ?>">
<div class="list-lft">
<div class="list-thamnail">
<?php if (has_post_thumbnail()) : ?>
<img width="" height="" class="list-img" src="<?php the_post_thumbnail_url('full'); ?>">
<?php else : ?>
<img width="" height="" src="sample.jpg">
<?php endif; ?>
</div>
</div>
<div class="list-rig">
<div class="list-cate">
<?php $categories = get_the_category();
if ($categories) : ?>
<?php foreach ($categories as $value) : $categories_id = $value->term_taxonomy_id; ?>
<span>
<?php echo $value->name; ?>
</span>
<?php endforeach; ?>
<?php endif; ?>
</div>
<p class="list-title">
<?php the_title(); ?>
</p>
<div class="list-date">
<?php if (get_the_time('Y/m/d') == get_the_modified_date('Y/m/d')) : ?>
<span class="entry">
<?php the_time('Y.m.d'); ?>
</span>
<?php else : ?>
<span class="update">
更新日:<?php the_modified_date('Y.m.d') ?>
</span>
<?php endif; ?>
<div class="list-view">
<?php echo getPostViews(get_the_ID()); ?>
</div>
</div>
</div>
</a>
<?php endwhile; ?>
<?php else : ?>
<p>まだデータがありません。</p>
<?php endif; ?>
関連記事を表示するコードサンプルです。
本記事では関連の仕様として同一カテゴリの記事をランダムで表示します。
single.phpの関連記事を表示したい箇所にコピペします。
使い方は以下の通りです。
関連記事を表示するのにWP_Query関数を使います。
WP_Query関数は任意の箇所にパラメータで要求した記事一覧を表示できる関数です。
以下パラメータを指定します。
'post_type' => 'post'
投稿タイプを指定します。(デフォルトはpost)
'post__not_in' => array($post->ID)
現在の記事ページを含めないようにします。
'category__in' => $category
現在記事のカテゴリを指定し、そのカテゴリの記事だけ表示します。
$category変数にはget_the_category関数で取得した現在カテゴリのIDを入れます。(上記サンプルコード参照)
'orderby' => 'rand'
新着順ではなくランダムで表示したい場合は上記を指定します。
最後にwhile文ループ内で取得したい記事の内容を入れます。
以上で関連記事の実装が完了です。
まとめ
関連記事を自作で実装する例を紹介しました。
手動で関連記事を選びたい方は以下記事をご参考ください。
以上で解説を終わります。