Display Random Post in WordPress Sidebar

We have been using plugins to display random posts on our sidebar. As all may have known, avoiding the use of plugins may decrease the loading speed of any wordpress website. We have started using these very simple line of codes just to make that happen. So how do we display random posts in WordPress sidebar without any plugins?

The Code

Just simply open you sidebar.php or on any file (eg:tab.php etc) where you need it to appear on sidebar and paste these codes.


<h2>Random Posts</h2>
<ul>
<?php $posts = get_posts('orderby=rand&numberposts=3'); foreach($posts as $post) { ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?><br />
<span><?php the_excerpt(); ?><br /><em>&mdash;Posted on <?php the_time('n/j/Y') ?></em></span></a>
</li>
<?php } ?>
</ul>

Simply troubleshoot, try and see how it looks like until you satisfy with it. Enjoy!

  • http://www.InfoGenra.com Raj

    I have used the same code, it is showing same posts for five times..

  • http://www.versedtech.org/ Sudip Majhi

    I think this code is not working for random posts. Its working as a recent posts widget.

  • Maurizio

    Hi Raj to prevent “the same posts error” i use this code
    display
    1,’orderby’ => ‘rand’, ‘showposts’ => 1));
    if (have_posts()) :
    while (have_posts()) : the_post();
    the_post_thumbnail(‘medium’); ?>

    by Maurizio