WordPress

How To Display Random Posts in WordPress using Code or Plugin

display wordpress random posts

Have you ever noticed that people visiting you blog are just reading you newly posted blogs while your old posts are just lying as it is. If you want to give your old posts a new life, how about displaying random posts in your blog for the user to choose. This way visitor will have the choice of multiple topics and you older post will also get the desired exposure. Doing this is pretty simple. Just follow the steps given below and you are all set!

display wordpress random posts

Please take a look at the code snippet below:

Code Snippet

<?php
  global $post;
  $postid = $post->ID;
  $args = array(
    'orderby' => 'rand',
    'cat' => 24,
    'showposts'=>5,
    'post__not_in'=>array($postid)
  );

  query_posts($args);
  echo '<ul>';
  while (have_posts()) : the_post();
    echo '<li><a href="'.get_permalink().'" title="'.the_title('','',false).'">'.the_title('','',false).'</a></li>';
  endwhile;
  echo '</ul>';
?>

The code snippet above is quite self-explanatory. The main function used to write this code snippet is query_posts($args). The parameters that are passed to function query_posts($args) are described below.

Parameters utilized

‘orderby’ => ‘rand’

This is basically MySQL RAND() function which produces the random lists of posts as desired.

‘cat’=>24

This parameter is used if you want to display posts in a particular category only. If you don’t want to limit the post display by category, don’t use this paramter.

‘showposts’=>5

This number restricts the number of posts that need to be displayed. In case you want lesser number of posts, change this to desired value.

You need to paste this snippet into your wordpress template so that it can work appropriately. The suitable and most used file to paste this snippet is your sidebar.php file or any other file you like.

Using WordPress Random Posts Plugin

In case you don’t want to get into the nitty gritty of code, then you can also use readily available wordpress plugin, available for the purpose. The plugin written by Rob Marsh is titled as ‘Random Posts’. You can download WordPress Random Posts plugin here.

display wordpress random posts

Please note that this plugin requires WordPress version 1.5 or higher. Be aware that excessive use of plugins in you site might slow it down, so be cautious while using plugins and use only whenever find absolutely necessary.

The good part with using code snippet is that it won’t have any affect your site performance.

Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

To Top