05
Aug
How to redirect users to a random post in wordpess
- Category:
- Wordpress

Posted On : August 5, 2013
| No Comment
What about giving a new life to your old posts by creating a page template that will redirect readers to a random post? Today, we are going to show you how to easily create this kind of page.
Create a new fine named with page-random.php and paste the given below code.
View Code PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // 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 ) ); exit; } |
Once done, upload the page-random.php file to your theme directory. Then, login to your WordPress dashboard and create a new page, called “random” (You have to call it random, otherwise, the standard page layout will apply).
After you published the random page, any user who’ll visit the http://www.yourwebsite.com/random page will be automatically redirected to a random post.
Once clicked on “random” page link it will redirect to a post. Here in given below figure “dummy post” is displaying.
Clicking again on same page link it will change post randomlly. Here in given below figure post has been changed.
- Tags: