In WordPress you can configure random post for your website random past means whenever a user will refresh a page or or click on a button they will get every-time new post, post will change randomly.
In this article I will show you how to Redirect users to random post.
First of all you have edit your WordPress function.php file. You can get function.php file in all WordPress theme.
After opening function.php file you have to add below code in function.php file.
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; } }
After adding above code you have to create a button that link to your domain such as www.example.com/random/ and the snippet above will take care of the rest.
307 Redirect is used for this redirection and it is temporary redirection. Browsers often cache 302 redirect which is famously known for temporary redirects.
If you have installed w3 Total Cache and you have enabled database caching, then you will need to add the following rules in the exclusion list.
/random/ /index.php?random=1
If you have installed Yoast’s WordPress SEO plugin then do not redirect ugly URLs checkbox in the permalinks area otherwise this code will break and will not work.
Thanks:)
If you find this tutorial helpful please share with your friends to keep it alive. For more helpful topic browse my website www.looklinux.com. To become an author at LookLinux Submit Article. Stay connected to Facebook.
Leave a Comment