Are you looking for a way to display a random post on your blog? While there’s probably a plugin for this, we have created a quick code snippet that you can use to list random posts in WordPress.
All you have to do is add this code to your theme’s index.php file:
<ul> <li><h2>A random selection of my writing</h2> <ul> <?php $rand_posts = get_posts('numberposts=5&orderby=rand'); foreach( $rand_posts as $post ) : ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endforeach; ?> </ul> </li> </ul>
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 50+ best responsive WordPress themes and how to create a custom user registration form in WordPress.
Comments Leave a Reply