Create a Random Post Button!

You can create a ramdom post button for your visitors. If you create this the visitors can click it and can read any of your posts! Read this tutorial and simply apply this codes. Let’s Begin!

Here is the code;

1st step:  Get your post from SQL

We will use sql command for get random post. Here is the command;

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

Explaining of this command;

guid: The URL of our post

wp_posts: The table of posts

post_type: This is the type of we get

post_status: Is this published? Yes

order by rand: Randomize of our request

Limit: We limited for 1 post.

2nd Step: Locate the php code where you want.

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

You can add this code where you want.
That’s All. Have a nice day!


Related posts:

If you enjoyed this post, make sure you subscribe to my RSS Feed
  1. Jun 20th, 2010 at 19:01 | #1

    I don’t understand where to add the code in the first step?

    • Jun 20th, 2010 at 23:07 | #2

      Hi my friend,

      First Step’s code is a SQL command. We use this code in 2.nd step’s full code. If You add 2nd code in your theme you can create a random post button. That’s All

  2. Jun 21st, 2010 at 00:20 | #3

    ok, thank you.

  3. grimmybee
    Jun 25th, 2011 at 00:12 | #4

    Hey. First off, thanks for sharing this – I discovered it a while back and it was exactly what I’d been looking for. I’ve been using it ever since but now I’ve run into a roadblock since renaming my blog’s URL and updating the relevant data. I’ve checked everything I can think of and can’t figure out why the ‘random’ link still points to the old address. I thought it might be a caching issue, but nope. My only other guess is that it’s related to the GUID – I did find occurrences of the old URL in the database but on the WP Codex page it recommends not changing them so I’m stuck. Any ideas/suggestions? Thanks in advance.

    • Jun 25th, 2011 at 12:08 | #5

      Yes the code calls “guid” for posts links. I think you can use a plugin for this. Platinum SEO Pack make 301 Redirect for old posts. Or you can use any plugin with which has a 301 Redirect.

  4. Lily
    Aug 11th, 2011 at 11:58 | #6

    Is there a way to modify this query to get the random post from a specific category?

    Thanks in advance!

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
 

Highslide for Wordpress Plugin