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
Comments are closed.
Highslide for Wordpress Plugin