Redirect to a Random Post in WordPress
In this note, I will show how to redirect users to a random post in WordPress.
For some types of sites, such as entertainment ones, where each post can be interesting and does not particularly become outdated over time, a page that shows a random post can be very useful.
This navigation will work as follows: you insert a link into the template, clicking on which will redirect the user to a random post.
Implementation
-
Insert the following code into the functions.php template file:
add_action( 'init', 'random_rewrite_rule' ); add_action( 'template_redirect', 'template_redirect_to_random' ); /* * Redirect to a random post */ function random_rewrite_rule() { $GLOBALS['wp']->add_query_var('random'); add_rewrite_rule('random/?$', 'index.php?random=random', 'top'); } function template_redirect_to_random() { if( get_query_var('random') != 'random' ) return; $random_post = get_posts('orderby=rand&numberposts=1'); $random_post = array_shift( $random_post ); $link = get_permalink( $random_post ); wp_redirect( $link, 307 ); exit; }
-
Go to the admin panel: Settings > Permalinks and simply click the "Save Changes" button. This is necessary to re-save the URL rewrite rules and add our new rule.
-
Insert the link http://example.com/random somewhere in the template. Or use this code:
<a href="<?php echo home_url() . '/random'; ?>">Random Post</a>
That's it! Now, by clicking on the link, the user will be redirected to a random post.
Notes for the Code
The code adds a query variable (add_query_var) for checking: redirect if the query variable exists and is equal to random. This check is used during the template_redirect event.
During redirection, status 307 (temporary redirect) is used instead of 302 (found), because some browsers cache the 302 status and in this case, the randomization will not work.
Possible Bugs
For page caching plugins, it may be necessary to specify exclusion rules: URLs that should not be cached. The rules will be as follows:
/random /index.php?random=random
That's all. I hope it will be useful to someone.