Older posts on your blog can “extend life” by creating a page template that will redirect readers to a random post. It may also be needed when a visitor wants to read something in the perspective of “useful”, but does not know where to start. Random post to help him 🙂In this article – a simple way to accomplish this. Create a new file and call it page-random.php . Paste the following code into it:
1 |
<?php |
2 |
// set the parameters for get_posts() |
3 |
$args = array ( |
4 |
'numberposts' => 1, |
5 |
'orderby' => 'rand' |
6 |
); |
7 |
8 |
// we take a random post from the database |
9 |
$my_random_post = get_posts ( $args ); |
10 |
11 |
//we run a request to the database through a cycle process foreach |
12 |
foreach ( $my_random_post as $post ) { |
13 |
// redirect the user to the random post |
14 |
wp_redirect ( get_permalink ( $post ->ID ) ); |
15 |
exit ; |
16 |
} |
17 |
?> |
Having done this, we upload page-random.php to the folder with your theme. Next, log in to the WordPress admin panel and create a new page, call it “random” (it should be called random, otherwise the standard template will be applied to the page, more information can be found in WP Codex to study the page hierarchy).
After the publication of this page, the user, clicking on the link http : // www . yourwebsite . com / random, will automatically be redirected to random blog entry.
An example can be seen in the menu or by clicking the Random post link.