If you’re blogging for some time now, you might notice that your old post are being forgotten and rotten in the very end of your website. Why not give them another chance to shine by randomly displaying your old post from your sidebar, you can try to use this on your custom WordPress theme. Today, we will learn how to display WordPress random post in your theme, this will be a very straight forward tutorial.
Start by opening your dashboard > appearance >editor and open your sidebar.php, now, add this piece of code.
<div class="sanz-random-post"> <h2>Check out our Random Post instead!</h2> <ul> <?php $posts = get_posts('orderby=rand&numberposts=5'); foreach($posts as $post) { ?> <li> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <?php the_post_thumbnail( 'category-thumb' ); ?> </a> <h3><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> </h3> </li> <?php } ?> </ul> </div><!-- sanz-random-post -->
This will display 5 random WordPress post, if you want to change it you can edit this part numberposts=5 and change the number to how many you wanted to display. You can also change the image according to your liking, I set my post-thumbnails to category-thumb because that’s the name of my thumbnails.
You can play around with the CSS to match your theme, here’s a simple styling that I did.
.sanz-random-post{} .sanz-random-post ul li{list-style-type: none;padding: 0;margin: 0;display: inline;} .sanz-random-post li{margin:10px 0;} .sanz-random-post li img{width:100px;float:left;vertical-align: top;} .sanz-random-post li h3 a{float: left;margin:0;color: inherit;} .sanz-random-post li h3 a:hover{color: inherit;}
If you’re the type that doesn’t want to touch the code, there’s other alternative plugin that you can use.
WordPress random post plugin
Spider Random Post
Spider Random Post allows you to show posts in a random order in a sidebar. You can display simultaneously as many random posts as you need.
Advanced Random Posts Widget
Provides flexible and advanced random posts widget. Allows you to display them with thumbnails, post excerpt, multiple category and more.
Random Posts Widget
Random Posts Widget Configurable
Hope this will be useful to you as it did to me. I used this code on my 404 page, so users who end up on the said page can see random post and Googlebot can index my old post, which is cool!
If you have more suggestion like this WordPress random post, you can hit me up in the comments below for questions.