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!
- Wordpress















Made by Symmetric Web
Distributed by Smashing Magazine
3 Responses
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.