Want your readers to browse more of your blog posts? If so, you might want to make browsing your blog a little more interesting than just navigating through post categories and archives.
A great way to spice things up (as far as site navigation is concerned) is to throw in a “random” post link that will jump the reader to a completely random post hosted on your blog/site.
The information for each WordPress post is stored in a local MYSQL database, and unlike most website applications and builds WP automatically has an integrated database (WPDB) which is set up during install. This means that there is no extra tinkering or source file editing required (besides adding in the random post link).
The Random Post Link Tag
WPDB makes things extremely easy; all we need to do is implement the code for the random post link which will use a MYSQL query. The following code can be added anywhere you would like the link to appear:
<?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>'; ?>
The following options can be changed in the code above to customize how the random link works:
AND post_status = ‘publish’- This basically tells WordPress to only select from posts with published status.
LIMIT 1- This decides how many total posts are displayed in the final results. If you would like more posts to be displayed you can change the number accordingly.
Style It Up
Remember to customize the style and output of the link before implementing the code on your WordPress enabled blog or site. As of now the link will only appear as text, in the “Random Post” form. If you would like to actually display the link as a button, you will need to implement the proper code before adding it to your site or blog.
Otherwise you now have a working link that will bring your readers to a completely random post on your WordPress blog or site.
My work here is done. Enjoy!