WordPress: Create a Random Post Button

No Comments

Photo of author

By admin

A good way to keep visitors on your website and reduce bounce rate is to use a “random post” button. This button can be used anywhere on your website (you can see ours in the sidebar), and when clicked it will take the visitor to a completely random post.

This is actually very easy to achieve, you simply add the following code into your theme’s function.php file:

add_action('init','random_post');
function random_post() {
       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;
       }
}

The create a link and put it in the desired location of your website. The link should look something like the following…

<a href="/?random=1">Random Post</a>

Leave a Comment