wordpressで、個別記事ページ(single.phpで表示されるページ)に、関連記事一覧を表示させる方法。
実現したいこと
カテゴリに階層がある場合、同階層のカテゴリに属する記事のみを表示したい。
↑このようなカテゴリ階層の場合、
「blog02」の記事の関連ページは、「blog02」に属する記事のみを表示させる。
「news」にだけ属しているページの関連ページは、同じく「news」にだけ属しているページになる。
こちらの質問に対する回答を参考にいたしました。
サンプルコード
上記サイトを元にしたコードはこちら。
最上部のカテゴリにしか属していない記事の場合の、関連ページの表示方法を追加しました。
コードの解説については、上記リンク先が詳しいです。
<!--relation-->
<?php
$cates = get_the_category();
$deepest = 0;
foreach($cates as $cate) {
$ancestors_ids = get_ancestors( $cate->cat_ID, 'category' );
$ancestor_num = count($ancestors_ids);
if( $ancestor_num > $deepest) {
$deepest = $ancestor_num;
$deepest_id = $cate->cat_ID;
}
}
if(is_null($deepest_id)){
$category_id = $cates[0]->cat_ID;
}else{
$category_id = $deepest_id;
}
$args = array(
'category__and' =>array($category_id),
'post__not_in' => array($post->ID),
'posts_per_page' =>4
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :?>
<div id="relationBox">
<section class="blogIndex">
<div class="tit">同じカテゴリーの記事</div>
<ul>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(); ?>
<p><?php the_title(); ?></p>
<span>- <?php echo get_the_date("Y.n.j"); ?></span>
<span>
<?php
$cats = get_the_category();
foreach($cats as $cat):
if($cat->parent) echo $cat->cat_name;
endforeach;
?>
</span>
</a>
</li>
<?php endwhile;?>
</ul>
</section>
</div>
<?php endif;
wp_reset_postdata();?>
<!--/relation-->
上記コードをメインループの下などに、サブループとして追加します。
今まであまり使っていなかった、get_ancestorsという関数について改めてリファレンスを確認しました。
最近の案件で使用したのですが、今後も使えそうなので自分用のメモとして記載しておきます。