How to display Random Post in WordPress

Sometimes we may need to display the random posts in Worpdress. If you do not use any plugin you just need to touch in php file page where the posts are being displayed. This random post can be applied not only default posts, it can be applied to any custom-post types also. So, just look where to change the code to be add/change for displaying random posts.

random-posts

First you need to ensure which post type you want to display randomly. Then you have to open that template and paste the below one line code before starting the loop:

 
query_posts(array('orderby' => 'rand');
//start your loop
if (have_posts()) :
while (have_posts()) : the_post();
//do your code inside loop
endwhile;
endif;

So you just need to change parameter value “orderby=>’rand’” which default set “orderby=>’date’”. Moreover if you use to call wp_query class then you need to set it inside your arguments:

 
$args= array('orderby' => 'rand', 'showpost' => 1, 'post_type' => 'post');
$wp_query = new WP_Query($args);
//start your loop
if (have_posts()) :
while (have_posts()) : the_post();
//do your code inside loop
endwhile;
endif;

In above example we mentioned our ‘post_type’ is “post” so if you wish to show your custom post randomly, just change the post type there. In addition, i also mentioned ‘showpost’ that is display only 1 post randomly in the loop. Maximum time people want to display single post or something link testimonial which will change each time page refresh. By this way we can make it. If still you have further issue to display post randomly just drop a comment, we will response within short time.

Thanks.

This post has already been read 5575 times!

Mehedi Hasan

Cool WordPress Developer having much agile experience to develop any kind of WordPress sites & plugins. Also good in troubleshooting, fixing & making any kind of tweaks for WP site.

More Posts

Mehedi Hasan

Cool WordPress Developer having much agile experience to develop any kind of WordPress sites & plugins. Also good in troubleshooting, fixing & making any kind of tweaks for WP site.

2 thoughts on “How to display Random Post in WordPress

  • December 18, 2014 at 1:54 am
    Permalink

    ohh.. i didn’t think that is so simple. That’s good Work Mehedi. Nice Post 🙂

  • August 11, 2015 at 5:14 am
    Permalink

    hi/ how can i display random month or week or daily posts?

Comments are closed.