How to create a ‘random posts button’ in WordPress

How to create a ‘random posts button’ in WordPress


Press a button and have WordPress serve you a random post!

The powerful & free WordPress open source blogging tool and content management system (CMS) based on PHP and MySQL, allows for various ways to output posts. One such way is by outputting a list of randomly selected posts using the MySQL RAND() function for the orderby parameter value in get_posts.

But what if you simply want to avoid displaying random posts on a page and just want to link to a random post?

Read on for a how-to after the jump.

First we will need to hook in our query variable, create the rewrite rule and the function for the random posts. Paste the following PHP code unto your WordPress functions.php file.

Note: For greater code maintainability, I recommend creating a new directory within your themes folder named “lib” i.e. /lib/, then creating a new PHP file within that /lib/ directory named function_wp_random_post.php holding the following code.

<?php
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;
}
}
?>

You can then call it in your functions.php with a simple PHP include call e.g., include(TEMPLATEPATH.'/lib/function-wp-random-post.php');

And link to it by creating a hyperlink like the following:

<a class="link-random" rel="bookmark" href="/index.php?random=1" title="Random article">Random article</a>

Or add it to a Widget by going to Appearance > Widgets within your WordPress Dashboard and simply dragging a text widget into your desired sidebar with the provided code above in that text widget.

In order to use the /random/ permalink or to customize it, you will need WordPress permalinks enabled. After which, you will need to edit your WordPress installation’s main root .htaccess file and change the standard .htaccess file from:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

to the following:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^random/ /index.php?random=1
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Looking at the above code, we simply added RewriteRule ^random/ /index.php?random=1 right after RewriteBase /

You can rename the random link URL to whatever you’d like. Make sure to edit function_wp_random_posts.php and your .htaccess file accordingly. Going forward, you’ll need to place a link to /random/ on your site:

<a class="link-random" rel="bookmark" href="/random/" title="Random article">Random article</a>

Note: If you are using the W3 Total Cache plugin with the database caching option on, then add the following rules in the exclusion list.

/random/
/index.php?random=1

Note: If you are using the WordPress SEO plugin by Yoast’s, make sure to have the option “Redirect Ugly URLs” on.

At this point, you should have yourself a phenomenal random post button for your WordPress website! A Live DEMO is available on my blog’s sidebar to check out.




About Giancarlo Colfer
Giancarlo Colfer
Affinity Media & Publishing Group's Founder & CEO

New York Experienced Professional Web Developer & Web Designer with over 18 plus years of experience in HTML, CSS, JavaScript, PHP and more.



Enjoyed this? Share this!

Subscribe to my RSS Feeds, Connect with me or simply recommend me to friends and colleagues!

  • digg
  • stumble
  • delicious
  • reddit
  • tumblr
  • pinterest
  • twitter
  • facebook

JOIN the CONVERSATION
3 Responses to “How to create a ‘random posts button’ in WordPress”

Be heard! Get involved and post your thoughts on WordPress today!

Read the comments left by other users below, or:


Guidelines: You share in the Affinity Media & Publishing Group, LLC community, so please keep your comments smart and civil. Do not attack other readers personally, and keep your language decent.

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

Signed in as [ Guest — Welcome! ]

AvatarNot sure how to get an image with your comment?

Terms of use: The views, opinions and comments posted are yours, and are not endorsed by this website. You shall be solely responsible for the comment posted here. The website reserves the right to delete, reject, or otherwise remove any views, opinions and comments posted or part thereof. You shall ensure that the comment is not inflammatory, abusive, derogatory, defamatory &/or obscene, or contain pornographic matter and/or does not constitute hate mail, or violate privacy of any person (s) or breach confidentiality or otherwise is illegal, immoral or contrary to public policy. Nor should it contain anything infringing copyright &/or intellectual property rights of any person(s).

2664 Comments

  1. Giancarlo Colfer Claudia said 4 years ago: Thank you, it is exactly what i was looking for! February 23, 2015 at 11:08am

No Pingbacks

Other websites linking to this article.

  1. thanks.

    Trackback by wayne— October 27, 2014 at 7:52 am
  2. thanks!!

    Trackback by jesse— November 12, 2014 at 8:13 am