A `/random` Route on a WordPress Site

UPDATE: If you have the Jetpack Plugin installed, all you have to do is add ?random (a URL param) and it’ll (contextually) randomize a single post. Wow. I had no idea. Thanks Chuck!

ANOTHER UPDATE: Jetpack has removed this feature now, so below might be useful again.


All I do to make this work on this site is make a page template:

<?php
/*
Template Name: Random
*/

$args = array(
  'orderby' => 'rand',
  'numberposts' => 1,
  'post_type' => array(
    'post'
  ),
);
query_posts($args);

while (have_posts()) : the_post();
  header('Location: ' . get_permalink());
endwhile;
?>Code language: PHP (php)

Then publish a page at that URL using that template.

Thoughts? Email me or comment below. Also CodePen PRO is quite a deal. šŸ™

6 responses to “A `/random` Route on a WordPress Site”

  1. Flo says:

    Nice trick!

    For all the lazy people – here’s the link: https://chris-coyier.mystagingwebsite.com/random

  2. ?random works on WordPress by default! :-)

    https://chriscoyier.com/?random

    I’m pretty sure this works in context, too. So if you append to the end of a category or tag archive page, it should return a random post in that category or tag.

Leave a Reply