関連記事は、関連度やタグもカテゴリも含むなど高度な設定が必要な場合はプラグインを使ったほうが早いかも。
ここでは簡単な関連記事の取得方法をまとめる。
プラグイン使わず関連記事を実装
functions.phpに以下のコードを追記。
// functions.php
function my_get_related_posts( $post_id, $related_count ) {
// 記事のカテゴリを取得、タグでも可
$terms = get_the_terms( $post_id, 'category' );
if ( empty( $terms ) ) $terms = array();
// カテゴリ一覧のslugを作成
$term_list = wp_list_pluck( $terms, 'slug' );
// クエリの設定、投稿タイプはパラメータで変更できるようにしても良い
$related_args = array(
'post_type' => 'post', // 投稿タイプ
'posts_per_page' => $related_count, // 表示数
'post_status' => 'publish', // 公開されてるもののみ表示
'post__not_in' => array( $post_id ), // 現在の記事を含めない
'orderby' => 'rand', // ランダム、DESCで新着順に変更可能
'tax_query' => array(
array(
'taxonomy' => 'category', // カテゴリから取得
'field' => 'slug', // $term_listでslugとってるので合わせる
'terms' => $term_list // カテゴリ一覧のslugを渡す
)
)
);
return new WP_Query( $related_args );
}
テンプレートに関連記事
あとはテンプレートの表示したい位置にループ処理を書き込むだけ。
<h1>関連記事</h1>
<ul>
<?php
global $post;
$wp_query = my_get_related_posts( $post->ID, 6 );
if ($wp_query->have_posts()) : while ($wp_query->have_posts()) :
$wp_query->the_post(); ?>
<li>
<a href="<?php echo get_permalink(); ?>">
<img src="<?php echo get_the_post_thumbnail_url(); ?>" alt="<?php echo get_the_title(); ?>">
<p><?php echo get_the_title(); ?></p>
</a>
</li>
<?php endwhile; endif; wp_reset_postdata(); ?>
</ul>