Title: 5 Random Posts
Last modified: August 19, 2016

---

# 5 Random Posts

 *  [craighton](https://wordpress.org/support/users/craighton/)
 * (@craighton)
 * [16 years, 8 months ago](https://wordpress.org/support/topic/5-random-posts/)
 * I wanna put on my sidebard 5 random posts that I’ve done. What is the PHP code
   for that?

Viewing 3 replies - 1 through 3 (of 3 total)

 *  [Clayton James](https://wordpress.org/support/users/claytonjames/)
 * (@claytonjames)
 * [16 years, 8 months ago](https://wordpress.org/support/topic/5-random-posts/#post-1234983)
 * [Display a list of 5 posts selected randomly](http://codex.wordpress.org/Template_Tags/get_posts#Random_posts)
 *  Thread Starter [craighton](https://wordpress.org/support/users/craighton/)
 * (@craighton)
 * [16 years, 8 months ago](https://wordpress.org/support/topic/5-random-posts/#post-1234987)
 * Is there a way that I can do 2 columns
 *  [Mark / t31os](https://wordpress.org/support/users/t31os_/)
 * (@t31os_)
 * [16 years, 8 months ago](https://wordpress.org/support/topic/5-random-posts/#post-1234997)
 * 2 columns of 5?
 * Sure.. i’ll take the example code posted on the link above to demonstrate one
   way..
 * First 5:
 *     ```
       <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 ) : $exc[] = $post->ID;
        ?>
           <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php endforeach; ?>
           </ul>
        </li></ul>
       ```
   
 * Second 5:
 *     ```
       <ul><li><h2>A random selection of my writing</h2>
           <ul>
        <?php
        $rand_posts = get_posts('numberposts=5&orderby=rand&exclude='.implode(',',$exc));
        foreach( $rand_posts as $post ) :
        ?>
           <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php endforeach; ?>
           </ul>
        </li></ul>
       ```
   
 * The first list creates an exclude list of post IDs as the list is built, the 
   second does the same as the first but loads in the post IDs to exclude, so you
   get 5 more random posts…
 * There’s a way you could do without doing 2 loops (using a counter), but the above
   was the easiest and quickest to type… 😉
 * If you want something done in one loop, post back and i’ll write another example..

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘5 Random Posts’ is closed to new replies.

 * In: [Fixing WordPress](https://wordpress.org/support/forum/how-to-and-troubleshooting/)
 * 3 replies
 * 3 participants
 * Last reply from: [Mark / t31os](https://wordpress.org/support/users/t31os_/)
 * Last activity: [16 years, 8 months ago](https://wordpress.org/support/topic/5-random-posts/#post-1234997)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
