X

Redirect home page to a random blog post

This is a slight mod of the wordpress post from yesterday (Redirect home page to first blog post) and think you might enjoy it. Add this snippet to the index.php template of your wordpress theme before get_header(). Your home page will automatically redirect to a random post from your wordpress database.


<?php 
if (have_posts() && is_home()) {
    query_posts('orderby=rand');
    while (have_posts()) {
        the_post();
        wp_redirect(get_permalink());
    }
}
?>

Comments  Leave a Reply

  1. Random Redirection in WordPress April 25, 2014 at 5:29 am

    […] “Redirect Home Page to a Random Blog Post,” WordPress Code Snippets […]

  2. I have been Googling all morning on how to make my blog display random posts on homepage and this truly done it! Thank you Kevin. You just saved me.

  3. Sweet code. I used this on my multisite install in a different way. I created a page template with this in it, then created a page with that template as the page template. I then added a “Random Post” button to the theme that all my multisites use that links to that page. So the result is a button that users can continually click to get to a random post on a random blog on the network. fyi this requires that you use the sitewide tags plugin to repost any posts from sub blogs onto the main blog. It sounds complicated maybe but it works great!

    1. Sweet sounds cool Paul, you could do something similar with this if you created a new template and page called random or something with the above. Hey you should submit a snippet or two we just recently add a contribute option – http://wpsnipp.com/index.php/contribute/

  4. Site of the Week: WPsnipp.com March 5, 2011 at 4:27 pm

    […] code snippets and shortcodes almost everyday of the week!Here are some of our favorite ones: Redirect a home page to a random post, show taxonomies as a list on a post or page, and disabling widgets on certain pages! Share and […]

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!