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!

I don’t understand where to add the code in the first step?
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
ok, thank you.
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.
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.
Is there a way to modify this query to get the random post from a specific category?
Thanks in advance!