Skip to content

Instantly share code, notes, and snippets.

@elhardoum
Last active March 25, 2016 01:41
Show Gist options
  • Save elhardoum/45995589811193fc3509 to your computer and use it in GitHub Desktop.
Save elhardoum/45995589811193fc3509 to your computer and use it in GitHub Desktop.
<?php
add_action('wp', function() {
if( '1' == get_query_var('se_random_post') ) {
$count = count( get_posts() );
if( (int) $count <= 0 )
return; // no posts
$picked = rand( 0, abs( $count - 1 ) );
$picked = (int) get_posts()[$picked]->ID;
if( get_post( $picked ) ) {
wp_redirect( get_the_permalink( $picked ) );
exit;
} else {
// try again (this may cause a redirect loop if no success pulling a random post)
wp_redirect( home_url('/random/') );
exit;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment