How To Redirect Users To A Random Post

a minute read

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.

Facebook Twitter LinkedIn Telegram Pocket

Related Posts:

Google changed the design of the AMP pages when viewed in search results. Now users can see direct links to publisher sites and share them. Google makes a copy of the AMP content and displays it from its own servers. The company claims that it allows you to sp...
Twitter introduces a new moderation policy, in accordance with which it will independently remove posts with offensive content, without waiting for complaints from users. According to a Twitter blog, the service can now identify 38% of abusive tweets. For comp...
A new study from Path Interactive revealed that organic search results on Google still attract the main attention of users. At the same time, younger people rely more on ready-made answers and knowledge panels, but rarely follow links to them. Experts called t...