Skip to content

Instantly share code, notes, and snippets.

@shizhua
Created August 24, 2015 07:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shizhua/97aaa25cde1fdee73460 to your computer and use it in GitHub Desktop.
Save shizhua/97aaa25cde1fdee73460 to your computer and use it in GitHub Desktop.
<?php
/**
* Function: Redirect to a random post
* URL: http://wpsites.org/?p=10370
* by Leo
*/
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;
}
}
?>
<?php
/**
* Template Name: Random Post
*
*/
?>
<?php
$args = array(
'posts_per_page' => 1,
'orderby' => 'rand'
);
$my_random_post = new WP_Query ( $args );
if ($my_random_post->have_posts()) :
while ($my_random_post->have_posts()) : $my_random_post->the_post(); ?>
<?php
wp_redirect ( get_permalink () );
exit;
?>
<?php endwhile;?>
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment