Is there any way to have a different post appear each time someone refreshes the home page of my self-hosted WordPress blog?
Currently I have the home page set to show only 1 post, but it’s only the latest one. I would like it to be different each time someone visits my site, to pull a post randomly from the archive of all posts.
Here’s what the loop currently looks like in the theme I’m using:
<?php
}
// Load main loop
if ( have_posts() ) {
// Start of the Loop
while ( have_posts() ) {
the_post();
?>
Is there any way to achieve this?
I also don’t want to keep the “Blog pages show at most 1 post” setting since that messes up my search results (every result is on a separate page) but I only want 1 post to show up on the homepage loop.
The best way is to modify the global query by hooking on pre_get_posts.
Insert this code into your theme’s functions.php:
This will check if you’re on home page, and if it is the main query (so only the main posts query is targeted), and if that is true, will set the
orderby
torand
, so each time a random post will appear on the home page.Please, note that if you have pagination on your home page, this will always order your posts in random order, so in this case you might want to build a custom query over your loop, by using the WP_Query class or query_posts().
Refer http://codex.wordpress.org/Template_Tags/get_posts