Skip to content

Instantly share code, notes, and snippets.

@elhardoum
Last active October 24, 2017 21:46
Show Gist options
  • Save elhardoum/49375e9329c66047f61c to your computer and use it in GitHub Desktop.
Save elhardoum/49375e9329c66047f61c to your computer and use it in GitHub Desktop.
<?php
add_action('wp', function() {
if( get_query_var('se_random_post') ) {
$post = get_posts(array('posts_per_page' => 1, 'orderby' => 'rand'));
$post = array_shift($post);
if( $post && $post->ID ) {
wp_safe_redirect( get_permalink( $post->ID ) );
exit;
}
}
});
add_action('init', function() {
// rewriting site.ext/index.php?se_random_post=1 to site.ext/random/
add_rewrite_rule(
'random/?$',
'index.php?se_random_post=1',
'top'
);
});
add_filter('query_vars', function($vars) {
// saving the query variable for the rewrite rule
$vars[] = "se_random_post";
return $vars;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment