Redirect users to a random page in WordPress

This might not be a standard feature of every WordPress website, but sure can be a fun tool to have somewhere on your site. If you write a lot or maybe have numerous galleries, you can end up having thousands of pages which an average user won’t get to see. So why wouldn’t you make things a bit more interesting with redirecting a user to a random post?

OK, you won’t be redirecting a user to a random post without their knowledge or do that on the homepage, of course. But you can create a simple button or link which a user can click after which he will be taken to another page of your site. Maybe it’s a gallery. Maybe a cool editorial you had written years ago. Who knows. It can be fun.

Let’s get started:

  1. First you need to prepare your redirect link. Open your functions.php file
  2. Copy and paste the following code:
  3. 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;
    }
    }
  4. Save changes
  5. Go to www.yourdomain.com/?random=1

After this, you are ready to create you link/button. All you have to do is link to http://www.yourdomain.com/?random=1 and every time a user opens the page, he will be redirected to a random page. Enjoy your new feature.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

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