Random Posts on your WordPress homepage

Random Posts in WordPress

WordPress by default displays posts in date order with Ascending or Descending options. What if you prefer to show random posts on your homepage so that every time someone visits your site, they see a different selection of posts.

First off, why would you want to do this. It could be that older posts on your site are just as relevant as newer posts and they don’t get read because they are buried too deep due to their date. While there are a number of plugins that offer this functionality, they usually offer this for widgets only. But what if I told you that you can do this with five lines of code.

Copy the code below and paste into your Child theme’s function file. That’s it.

add_action('pre_get_posts','alter_query');
function alter_query($query){
if ($query->is_main_query() && is_home())
$query->set('orderby', 'rand'); //Set the order to random
}

One response on “Random Posts on your WordPress homepage

  1. wmasat

    I have a buddypress with a theme(youzify), I want to display activitys posts randomly on home page, I want posts to be displayed randomly, not in chronological order
    anyone knows any code or method for that

Leave a Reply

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