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 $my_query = new WP_Query('posts_per_page=1&orderby=rand'); while ($my_query->have_posts()) : $my_query->the_post(); ?> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <?php the_content(); ?> <?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.