DEV Community

kumamon
kumamon

Posted on

【WordPress】同じカテゴリ内でランダムに関連記事生成

<div class="newcontentarea">
<?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'=> 6,
  'category__in' => $category_ID,
  'orderby' => 'rand', // ランダムに記事を選ぶ
);
$query = new WP_Query($args);
if( $query -> have_posts() ): while ($query -> have_posts()) : $query -> the_post();
?>
<div class="newcontentarea2">
<a href="<?php the_permalink();?>">
    <div class="newcontentarea3">
        <div class="innerarea">

    <?php if(has_post_thumbnail()): ?> 
    <?php the_post_thumbnail(); ?>
<?php else: ?>
    <img class="lazyload" data-src="★★NOIMAGEパス★★" alt="no image">
<?php endif; ?>
    <h3><?php the_title();?></h3>
        </div>
</div>
    </a>
 </div>       
<?php endwhile; endif; ?>
<?php wp_reset_postdata(); ?>

</div>

Oldest comments (0)