Wednesday, March 20, 2013

How to redirect users to a random post

How to redirect users to a random post

To do this follow the instruction below
Create a new file and name it page-random.php and just paste the code below in it:

// set arguments for get_posts()
$args = array(
    'numberposts' => 1,
    'orderby' => 'rand'

// get a random post from the database
$my_random_post = get_posts ( $args );

// process the database request through a foreach loop
foreach ( $my_random_post as $post ) {
  // redirect the user to the random post
  wp_redirect ( get_permalink ( $post->ID ) );

Now, upload the page-random.php file to your wordpress theme directory. After upload login to your WP dashboard and create a new page, called "random" [If you dont call it random, otherwise, the standard page layout will apply, you can check Wordpress Codex for more details about page hierarchy].

Now after you published the random page, if any user  visit the page, he will be automatically redirected to a random post.

No comments:

Post a Comment

I just got my #domain @BigRock. Get upto 25% off with my personalized coupon link Get upto 25% off