In some cases, you may want to display a random post on your WordPress site. In order to make this happen, we can create a new query using the WP_Query function. WP_Query gives you the ability to create multiple loops on any given page of your site, without conflicting with the existing loop.
Use the following code on any page and/or sidebar to display a single random post anywhere on your site.
<?php
$the_query = new WP_Query('posts_per_page=1&orderby=rand');
while ($the_query->have_posts()) : $the_query->the_post(); ?>
<article>
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
</article>
<?php
endwhile;
wp_reset_postdata();
?>
As always, with WordPress there are multiple solutions to almost every problem. If you have an alternative solution to using WP_Query, please feel free to share.
Thanks that is exactly what I wanted to know!!
Thank you. This is just what I needed.