
How to Display Random Blog Posts in WP without a Plugin
- October 27, 2015
- Leave a comment
Posts in WordPress are just like the content or type of data which is used by many bloggers on their websites. Bloggers use posts to describe their different types of articles. By default , WordPress shows blog posts in a chronological order (means that latest added post with respect to time will show first).
In this article, we are going to change this default behavior to random one so that all your posts will be shown to you in a random manner. They will neither be in ascending nor descending order.
In order to fetch the random posts, you have to write a query. This query will retrieve the posts accordingly. For writing a query, you have to use the WordPress function “query_posts()”. See the code written below so that you will understand it better:
1 2 3 |
<?php query_posts( array ( 'orderby' => 'rand', 'showposts' => 5 )); ?> |
As you can see “query_posts()” function has an array and this array consists two things:
- Orderby = ‘rand’
- Showposts = 5.
Orderby = ‘rand’ is very important as it is related to our topic and it will show your posts in a random manner. Showposts = 5 is related to the number of posts that how many posts you want to display in a random manner. As n this example it is set to 5, so it will display only 5 posts. You can change it according to your will.
Now you need to assign this query function to the variable in order to achieve the required result:
1 2 3 |
<?php $result= query_posts( array ( 'orderby' => 'rand', 'showposts' => 5 )); ?> |
You have stored all the random posts in “$result” variable. The next step is to fetch these posts using a loop. Now to apply a loop for fetching the records, see the code below for achieving the result:
1 2 3 4 5 6 7 8 |
<?php $result= query_posts(array('orderby' => 'rand', 'showposts' => 5)); if ($result->have_posts()) : while ($result->have_posts()) : $result->the_post(); ?> <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2> <?php the_content(); ?> <?php endwhile; endif; ?> |
From the above code, “$result” variable has every one of the posts went on a condition which checks that if your post exists, then move it to the loop and give all records of containing the random posts.
User Comments