WordPress

関連記事の表示(同じカテゴリから)

更新日:2026-05-04 著者:unigram 読了目安:2分

同じカテゴリから記事をランダムで表示する方法

<?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'=> 7,//取得する件数
		'category__in' => $category_ID,
		'orderby' => 'rand',//ランダムに記事を選ぶ
	);
	$query = new WP_Query($args);
	if( $query -> have_posts() ):
	while ($query -> have_posts()) :
	$query -> the_post();
?>

<!-- ここに記事コンテンツ -->
<div class="post">
    <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('thumbnail'); ?></a>
    <h2 class="title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
</div>

<?php endwhile; ?>
<?php else : ?>
<?php endif; wp_reset_postdata(); ?> 

この記事を書いた人

unigram
web、印刷、映像などの制作をしています。@京都、フリーランス18年目。 大学で講師もしています。 自身の備忘録も兼ねて、Web制作・WordPress・SEO・GA4・生成AI活用をテーマに情報発信しています。わかりやすく優しい内容で記事作成を心がけています。