If you stumble across the web a lot, especially blogs – you may already have come across menu links or buttons that say ‘random’ or ‘feeling lucky’ – what they do is to send you to a random blog post. Magic ? No !

Here is how you can do this – Go to your WordPress Dashboard > Appearance > Menus. Now create a new custom link and add it to the menu of your choice. In the URL field, type in the base url of your blog like http://www.your-blog.com and extend it with a route like ‘/random‘ . See the image below on how I did it:

Next, go to Appearance > Editor and locate the function.php file of your theme. Best idea is to put your own function all the way down at the bottom of the function.php file. Please remember: as the following code snippet is very simple, it’s very unlikely that something bad happens, however please use at your own risk. Copy paste the following PHP code into your functions.php file:

function random_add_rewrite() {
       global $wp;
       add_rewrite_rule('random/?$', 'index.php?random=1', 'top');

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);

Hit save and you’re done. The first part of this code, catches the /random route and sends you to a random post of your blog, the second part updates the url in the browser.

Leave me a comment if you have any questions.