Home Articles How to make a random post button

How to make a random post button

5210
146
SHARE

Ever wanted to have a “Random Post” link or button in your sidebar but you don’t know where to start? Well, today I’m going to show you how to do it.

The principles

As you may know already, WordPress posts are stored in a MySQL database. For us to obtain the URL to a random post from that database, we need to run a MySQL query. It’s pretty simple actually, thanks to WPDB, a built-in database class that comes with every WordPress install, we don’t need to bother about database names, passwords, connections and disconnections, etc. We just need to run the query and echo the result.

The MySQL query

Our database query needs to look inside the posts table and select one random post from the published posts. This is what the query looks like:

SELECT guid FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY rand() LIMIT 1

Let me explain how exactly this MySQL query works:

  1. SELECT guid – Select just the guid column value, which is where the URL to the post is located.
  2. FROM wp_posts – From the posts table
  3. WHERE post_type = 'post' – Since attachments are also saved in the posts table, we need to specify that we just want posts
  4. AND post_status = 'publish' – We just want the published posts, not scheduled posts, not drafts
  5. ORDER BY rand() – Get them in random order
  6. LIMIT 1 – And get just one result

The PHP code

Now, let’s type the PHP code. As I said, we’re going to make it simple by using the WPDB class, which comes bundled into WordPress. This is our code:

get_var("SELECT guid FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY rand() LIMIT 1");
echo 'Random Post';
?>

In the first line of the code, we’re running the database query using the WPDB get_var() function, and storing the result inside a $randomPost variable. Then, in the second line, we’re echoing the link, pointing to the URL stored in the $randomPost variable.

Note I’m using $wpdb->posts instead of wp_posts, that way, we make sure that we’re selecting the right table, since you could have changed the table prefix (which by default is ‘wp_’).

That’s it for today. I hope you enjoyed the mini-tutorial.

146 COMMENTS

  1. If you want to do this using the WordPress API, it’s fairly straightforward:

    'rand', 'showposts' => 1)); ?>
    <a href="">Random Post

    I would also caution against using the GUID field of wp_posts as a permalink. At the moment, it happens to be a permalink to the post, but as a globally unique ID, it could just as well be a string of characters like “3F2504E0-4F89-11D3-9A0C-0305E82C3301,” and it may end up that way in future versions of WordPress.

  2. Erg. Well, here’s the relevant code, and I’ll stop spamming your comments.

    The query:

    query_posts(array('orderby' => 'rand', 'showposts' => 1));

    The part that prints the link:

    the_post(); the_permalink();

  3. @Austin: Indeed, that would be the right way to do it, I just felt it would be easier to just do a database query… Avoid a second loop, problems, you know… 😉

  4. I need to do a link, which changes the post status to “published” and refreshes the post.
    Has some1 an idea??

  5. Is there a way to EXCLUDE certain post. I thought I could add something like AND ID(‘1′,’2′,’3′,’4’) AND…. doesn’t seem to work. My sql skills are sadly my weakness

  6. I’d like to know the same as the above commenter. This is very helpful but what if I wanted to exclude certain categories?? How would that change the query?

    Thanks!

  7. Hi,

    I’ve made a random post creating an array with all the old post ids, but I did that taking the post ids almost by hand from the database exported CSV file. This way I could use javascript with the “?p=” syntax and the server dont bother me about exceeding processor time, etc.

    Do you a clever way to extract the post ids from wordpress database without the post ids from images?

    [ ]s

  8. Hey mate, thanks a lot for this! I’ll be using it on my new website, DailyVibes.net – site will utilize WP to display three songs every weekday… this button will come in handy when I have a lot more posts down the road.

    I’ll be putting a backlink to your site as my way of saying thanks! Here’s to the future 🙂

    -Ryne

  9. I just used this on my blog and it worked perfectly. Took about 2 seconds to put into the code and worked first try. THANK YOU SO MUCH!

  10. Hey.
    I’m a total noob when it comes to all of this.
    I’m guessing that the neato little PHP that you created goes into the sidebar.php file of any WP theme.
    BUT it didnt show up in mine when I uploaded the file to FTP, and there wasnt a new widget in my sidebar widget area when I refreshed my WP editor … Did I totally miss something here?

        • OMG!
          I got it!…just playing with sidebar today trying to work around a totally different issue. I was trying to put the Random Post button in the widget area using the unordered list. I took the code you provided out of that list and placed it under my makeshift “home” button…VOILA!
          THANK YOU!!! YOU ROCK!

          ~The Sultana of Sizzle (Andrea

  11. Great tutorial!
    Is there any way to use PHP and SQL like this (not necessarily just this, although it is a VERY interesting feature) if you only have a free WordPress account, or do you need to shell out the cash and go pro to start modifying your blog in this way?

    Sincerely,
    A metalhead with a blog.

    • Hey there, I think your site might be having browser compatibility issues.
      When I look at your blog site in Ie, it looks fine but when opening in Internet Explorer,
      it has some overlapping. I just wanted to give you a
      quick heads up! Other then that, terrific blog!

      webpage (Shonda)

  12. Hey man, awesome tutorial, I’m trying to do the same thing on my site. I have the button working perfectly but when I click on the”random article” everyonce in a while it will take me to my old wordpress site.

    tekbull.wordpress.com instead of my actual site tek-bull.com is there a way to exclude the tekbull.wordpress.com from the results?

  13. I have just started working on my first blog and trying to learn as much as possible so that i can get the blog setup and running smoothly. Learned something great and new from this post.

  14. As trees are growing yellow and leaves begin to dance in the air, autumn comes here elegantly from the distance. Her aroma recalls me the precious memory, which is flower blossoming in my whole life.

Comments are closed.