How to get random Posts in WordPress


WordPress introduced WP_Query class in its version 1.5.0 for the custom query. It gives the leverage to execute the custom query. It also helps to fetch the random post in WordPress. WP_Query accept the single argument or array of arguments.

Follow the below steps to get random posts in WordPress.

Step 1: The first step is, we have to prepare your query.

<?php
	$random_post_query = new WP_Query(array(
		'posts_per_page' => 8,
		'orderby' => 'rand'
	));
?>

posts_per_page » fetches the number of records you have specified.

orderby » specify the order of the posts.

Step 2: Before looping the query, do a check whether the query contains posts or not.

<?php if ($random_post_query->have_posts()) : ?>

Step 3: If the query contains post, loop through it.

<?php while ($random_post_query->have_posts()) : $random_post_query->the_post(); ?>
	<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
	<p> 
		<?php echo get_the_excerpt(); ?>
		<a href="<?php the_permalink(); ?>">Continue reading »</a>
	</p>
<?php endwhile; ?>

Step 4: Restore/reset the WordPress query to the normal flow.

<?php wp_reset_postdata(); ?>

wp_reset_postdata() function restores the $post global to the current post in the main query.

Step 5: Close if-else block.

<?php else : ?>
<?php endif; ?>

See the complete example.

<div class="mt-4">
    <?php
		$random_post_query = new WP_Query(array(
            'posts_per_page' => 8,
            'orderby' => 'rand'
        ));
    ?>
	
    <?php if ($random_post_query->have_posts()) : ?>
	
	<?php while ($random_post_query->have_posts()) : $random_post_query->the_post(); ?>
	
        <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
        <p> 
			<?php echo get_the_excerpt(); ?>
            <a href="<?php the_permalink(); ?>">Continue reading »</a>
        </p>
    <?php endwhile; ?>
	
    <?php wp_reset_postdata(); ?>
	
    <?php else : ?>
    <?php endif; ?>

</div>

References

  1. WP_Query
  2. wp_reset_postdata()

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.