ControlledChaos of Controlled Chaos Design
8/9/2016 - 6:46 PM

Redirect to a random post.

Redirect to a random post.

<?php

function ccd_random_add_rewrite() {
  global $wp;
  $wp->add_query_var( 'random' );
  add_rewrite_rule( 'random/?$', 'index.php?random=1', 'top' );
}
add_action( 'init','ccd_random_add_rewrite' );

function ccd_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;
  }
}
add_action( 'template_redirect','ccd_random_template' );

?>

Redirect to a Random Post

WordPress Snippet