Like we all know, WordPress is powerful publishing platform. Now everywhere is WordPress, blogs, portal, e-commerce and many more running on WordPress. WordPress is amazing and multi user. Now we will show you how to redirect user into random post in WordPress.
We only needed tiny script that we need to put on functions.php. Mostly on newest wordpress theme already have functions.php on the theme folder. So open that file and added this code
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;
}
}
That’s it. Now you have done with most important step on this tutorial. Now if you want enable this is super easy. Create new link that link to http://yourdomain.com/random and when this link click user will get random content from your blog post. That easy right? Thanks for WP Beginner to share this tricks.
Please notest if you are using W3 Total Cache you need to add this code on the exclude list.
/random/ /index.php?random=1



