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 ) );
exit;
}
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 http://www.website.com/random page, he will be automatically redirected 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 ) );
exit;
}
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 http://www.website.com/random page, he will be automatically redirected to a random post.
No comments:
Post a Comment