【WordPress・PHP】関連記事一覧を表示する自作コード

この記事は分で読み終わります。

ワードプレスで関連記事を表示させるためのソース。
$args = array(中を変える事でカスタマイズできます。);

関連記事の表示

記事下などによく利用されています。

<?php

$categories = get_the_category($post->ID);
$category_ID = array();
foreach($categories as $category):
array_push( $category_ID, $category -> cat_ID);
endforeach ;
$args = array(
'post__not_in' => array($post -> ID), //現在の記事を含めない
'posts_per_page'=> 4,           //関連記事の表示数
'category__in' => $category_ID,        //カテゴリIDを指定
'orderby' => 'rand',                   //ランダム表示
);
$query = new WP_Query($args); ?>

<div id="related-box" class="original-related">
<h2 class="related-h h_ttl"><span class="gf"><?php the_category(); ?></span></h2>
<?php if( $query -> have_posts() ): ?>
<ul>

<?php while ($query -> have_posts()) : $query -> the_post(); ?>
<li class="related_newpost__li">
<a href="<?php the_permalink(); ?>">
<figure class="eyecatch">
<?php if (has_post_thumbnail()){
the_post_thumbnail('oc-post-thum');
} else {
echo oc_noimg();
}
?>
<?php echo stk_archivecatname();?>
</figure>
<?php echo stk_archivesdate();?>
<div class="ttl<?php echo stk_post_newmark();?>"><?php the_title(); ?></div>
</a>
</li>
<?php endwhile;?>

</ul>
<?php else:?>
<p>関連記事は見つかりませんでした。</p>
<?php endif;?>
</div>

<?php
wp_reset_postdata();

?>

カスタマイズするには

$args = array(
'post__not_in' => array($post -> ID), //現在の記事を含めない
'posts_per_page'=> 4,           //関連記事の表示数
'category__in' => $category_ID,        //カテゴリIDを指定
'orderby' => 'rand',                   //ランダム表示
);

カスタマイズするには上記を修正します。

‘posts_per_page’=> 4, の4を10に変更すると関連記事が10記事表示されます。

‘category__in’ => $category_ID,は変数ではなく数字で指定する事もできます。

©Copyright2022 FICH-LABO.All Rights Reserved.