Blog

【WordPress】記事をランダムに表示させる方法

2013.10.22 2020.10.25 WordPress

記事を一覧表示するページで、条件に合う記事を取得しランダムに表示する方法です。カテゴリーページなどで過去の記事が埋もれてしまうことなく、ユーザーの目に届きやすくなります。

以下のような感じで指定します。あなたの場合に当てはめて書き換えてみてください。

記事をランダムに表示する

<?php query_posts('orderby=rand');?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
    <div class="post"><?php the_content(); ?></div>
<?php endwhile; ?>
<?php else: ?>
    <h2>記事がありません</h2>
<?php endif; ?>

カテゴリーIDが5の記事をランダムに表示する

<?php query_posts('cat=5&orderby=rand'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
    <div class="post"><?php the_content(); ?></div>
<?php endwhile; ?>
<?php else: ?>
    <h2>記事がありません</h2>
<?php endif; ?>

記事をランダムに10件表示する

<?php query_posts('showposts=10&orderby=rand');?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
    <div class="post"><?php the_content(); ?></div>
<?php endwhile; ?>
<?php else: ?>
    <h2>記事がありません</h2>
<?php endif; ?>

カテゴリーIDが5の記事をランダムに10件表示する

<?php query_posts('cat=5&showposts=10&orderby=rand');?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
    <div class="post"><?php the_content(); ?></div>
<?php endwhile; ?>
<?php else: ?>
    <h2>記事がありません</h2>
<?php endif; ?>