How To Redirect Users To A Random Post

2 minutes 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:

To boost a post on Facebook means reaching a larger audience by paying to promote it. Here&#39;s a step-by-step guide on how to boost a post:Create the post: Start by creating the content you want to boost. It can be a text, photo, video, or link. Make sure it...
To post content on a user&#39;s Facebook timeline via API, you need to follow these steps:Obtain the necessary permissions: In order to post on a user&#39;s timeline, you must obtain the &#34;publish_actions&#34; permission from the user. This permission allow...
To schedule posts on Facebook, follow these steps:Start by logging into your Facebook account.In the &#34;Create a post&#34; box at the top of your News Feed, type your post.Once you&#39;ve finished typing your post, you will notice a small arrow next to the &...