Social Networks

I got one tutorial request about how to redirect users to a random post in WordPress  sites?  WordPress supports random redirection out of the box, but it’s not very obvious.  You can do this  by creating a page template that will redirect readers to a random post. To implement random redirection in WordPress, you will usually need to work with the following three steps:


Step 1: A page to process the redirection

Create a new file and name it page-random.php. Paste the code below in it:


// set arguments for get_posts()
$args = array(
    'numberposts' => 1,
    'orderby' => 'rand'
// get a random post from the database
$my_random_post = get_posts ( $args );
// process the database request through a foreach loop
foreach ( $my_random_post as $post ) {
  // redirect the user to the random post
  wp_redirect ( get_permalink ( $post->ID ) );

Step 2: A query to pick a post from the database

Once done, upload the page-random.php file to your theme directory. Then, login to your WordPress dashboard and create a new page, called “random” (You have to call it random, otherwise, the standard page layout will apply

Step 3: Some sort of mechanism to initiate the redirection

After you published the random page, any user who’ll visit the page will be automatically redirected to a random post.

We can now add a link in the main menu to make the page easily accessible.

This is the easiest way to discover any post/article from your site. Thanks to Smashing Magazine for the cool tip!

None found.

Leave a Reply

Your email address will not be published. Required fields are marked *

Allowed Tags:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>