Display Random Posts on Single.php Page

Displaying random posts on post page (single.php) is a very common practice now a days. In case if your theme doesn’t have that functionality by default, you can easily add them using very simple snippet. I have used the following snippet on many blog sites that I have designed and it worked right out of the box.

<div id="random-posts">
<h2>Random Post</h2>
  <?php $posts = get_posts('orderby=rand&numberposts=5'); 
   foreach($posts as $post) { ?>
  <li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
  <?php the_title(); ?></a></li>
 <?php } ?>

This is fairly simple and easy to implement on your site. All you need to do is to copy and paste the above snippet on your theme’s single.php page. Definitely, where you want to place them and how exactly you want them to show up is entirely up to you.

What about Custom Post Type?

Things might get little more complicated if you want to display random posts from a Custom Post Type (CPT). Let’s assume, you have registered a CPT called “books”, where you want to write review of various books that you have read. Now when a visitor would be reading a book review post, you also might want to suggest some other review articles that you have written under the same CPT.

To do so, add the following snippet on your “single-books.php” (single page for books CPT) page.

<div id="random-books-review">
<h2>Random Books Review</h2>
$args = array (
   'post_type' => 'books',
   'posts_per_page' => '5',
   'orderby' => 'rand',);
$mrbr = new WP_Query($args);
if ($mrbr->have_posts()) { ?>
<ul><?php while ($mrbr->have_posts()) { $mrbr->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php } ?></ul>
<?php } wp_reset_query(); ?>

All we did over here is, querying posts. On arguments we mentioned the post_type must be “books” and asking the query to select 5 posts and display them randomly. Yes, you can change the number of posts/review that you want to display. Now, you can design the <div> anyway you want with CSS.

Note: You can use the second snippet to query the regular blog posts as well. All you have to do is the make simple adjustment on your arguments. Change the value of “post_type” parameter with “post” replacing “books”, that’s it.

Today In History



Leave a Reply

Note: Convet HTML, PHP, JavaScripts from HTMLify, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.