How to Redirect Users to a Random Post in WordPress

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.

function random_add_rewrite() {
global $wp;
add_rewrite_rule('random/?$', 'index.php?random=1', 'top');

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);

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.


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.


Thank you! for visiting LookLinux.

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 Look Linux Submit Article. Stay connected to Facebook.

About the author


Santosh Prasad

Hi! I'm Santosh and I'm here to post some cool article for you. If you have any query and suggestion please comment in comment section.

Leave a Comment