PressTigers

How to Display Random Blog Posts in WP without a Plugin

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 functionquery_posts()”. See the code written below so that you will understand it better:

As you can see “query_posts()function has an array and this array consists two things:

  1. Orderby = ‘rand’
  2. 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:

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:

From the above code, “$resultvariable 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

Leave a Reply

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

Get in Touch