How to create a random post link in your blog

April 3rd, 2015 Raj 0 Tips

One of the reason to add a random post link button on your blog is to allow your visitors to browse through your site in a random way. Visitors some times want to get surprised at what they want to see, and in that case this random post link can come handy.

Believe me or not, people do click on these buttons, and creating such buttons are quite easy if you know what you are doing.

Step One: Create an eye-catching button
First decide where you want to place your random post button, then keeping that dimension in mind create a good looking button, or you can just simple add a link to your navigation or you can add link to your sidebar. Check out how you can create good looking buttons through css3.

Step Two: Add coding to a widget
For our example lets add a random post button to our sidebar. Head over to Appearance > Widgets and add a text widget to your sidebar. Then paste your code in and click save. You have added your button to sidebar.

Step Three: Add coding to your blog.
Before making this step, make sure you backup your theme via ftp, so that in any case if you mess up, you had a point where you can return and fix things.

When you have taken the backup of your theme, open functions.php in a text editor and at the very bottom of that page add the following code after } add few return/enter keys to create new lines and add the following code there.

add_action('init','random_add_rewrite');
function random_add_rewrite() {
       global $wp;
       $wp->add_query_var('random');
       add_rewrite_rule('random/?$', 'index.php?random=1', 'top');
}
 
add_action('template_redirect','random_template');
function random_template() {
       if (get_query_var('random') == 1) {
               $posts = get_posts('post_type=post&orderby=rand&numberposts=1');
               foreach($posts as $post) {
                       $link = get_permalink($post);
               }
               wp_redirect($link,307);
               exit;
       }
}

Second Way:

If you don’t want to mess around with functions.php file, then there is another way for you.

Step One: Create a new template file
Create a new template file, name it say random.php with the following content.

/*Template Name: Random Post*/

$posts = get_posts('post_type=post&orderby=rand&numberposts=1');
foreach($posts as $post) {
	$link = get_permalink($post);
}
wp_redirect($link,307);
exit;

Step Two: Create a wordpress page
Create a page name it say “Random”, select the template “Random Post” and publish.

Step Three: Add coding to a widget
For our example lets add a random post button to our sidebar. Head over to Appearance > Widgets and add a text widget to your sidebar. Then paste your code in and click save. You have added your button to sidebar.

You can see the working example for random post in this blog.