How to display random posts in WordPress

Usually, people show their most recent posts which can be easily done via WordPress widget which comes as standard WP feature. When that’s not enough, you can manually add the code which will show recent posts or you can install a plugin which will do the job for you.

While showing recent posts is really popular and effective, sometimes you will want to sort your posts differently. For example, you might want to display the most commented posts from a specific category.

But what if you wanted to show posts in no particular order? Instead of sorting posts by their name, category, tags or their date, you could randomly take one of your posts and display it on the sidebar, in the widget or directly in your post.

In today’s article, we’re about to show you a simple PHP function which will do exactly that:

  1. Open sidebar.php, text widget or any location where you want to display your random posts
  2. Copy and paste the function:
  3. <?php
    $args=array(
    'cat' => 1,
    'orderby' => rand,
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 4,
    'caller_get_posts'=> 1
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) : $my_query->the_post(); ?>
    <p><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_post_thumbnail(); ?><?php the_title(); ?></a></p>
    <?php
    $name = get_post_meta($my_query->post->ID, 'WritersName', true);
    if ($name){
    echo 'Writers name: ' .$name;
    }
    endwhile;
    }
    wp_reset_query();  // Restore global post data stomped by the_post().
    ?>
  4. Change details in $args array
  5. Save changes

After you have copied the function on the desired location, you can decide how to show those random posts. The part you are interested in can be found in the array on top of the function.

Current example shows 4 random posts from category with the ID=1. If you wanted to show random posts from a specific category, simply change the ID number of desired category. In case you want to show random posts from your entire collection, simply remove  ‘cat’ => 1, row from the array.

That’s all. After you hit the save changes button, your posts will be randomly selected each time you refresh the page. Really cool function, isn’t it?

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

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