BlaPageBlaPage
It's about Internet – SEO, Black Hat SEO, Wordpress, Personal Computers, Technology, WebHosting

Redirect WordPress Visitors to Random Post

We will create a button on our site so if a user clicks on that button, they are taken to a random post on your website.

For this Open your theme’s functions.php file or create a blank plugin file and paste the following 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;
       }
}

Few bugs

If you are using W3 Total Cache and you have database caching on, then you need to add the following rules in the exclusion list.

/random/
/index.php?random=1

If you are using Yoast’s WordPress SEO plugin, then don’t use Redirect Ugly URLs checkbox in the permalinks area otherwise this code will not work.

Hope this BlaPage was helpful, Redirect WordPress Visitors to Random Post.


Link To This BlaPage From Your Website :

Category: Customizations, Php, Wordpress

Tagged: ,

Comments are closed.

Facebook FanPage

Follow BlaPage on Twitter