Post
  • ecommerce
  • php
  • web development
  • Wordpress
  • wordpress hooks

How to Redirect to Random WordPress Post everytime?

In this article, we will explore a method to redirect to random WordPress post by simply appending “/?random” to the URL. This feature can be particularly beneficial for individuals looking to share posts on their social media accounts. Rather than navigating through your blog or articles and manually copying a specific post’s URL, this approach […]

   
How to Redirect to Random WordPress Post everytime?

In this article, we will explore a method to redirect to random WordPress post by simply appending “/?random” to the URL. This feature can be particularly beneficial for individuals looking to share posts on their social media accounts. Rather than navigating through your blog or articles and manually copying a specific post’s URL, this approach provides an efficient way to open a random blog post URL. When a user enters “/?random” in the URL, the system will automatically redirect them to a random selected post by using wp_redirect hook. The hooks in the WordPress plays an important role in providing custom functionalities in the website. Developers used both the action and filter to improve the functionality of their client’s site.

1. First, go to the functions.php file of your active WordPress theme. In this file, we will write a custom function that detects the “/?random” parameter in the URL and redirects the user to a random post URL.

function custom_redirect_on_parameter() { 
{
 if (strpos($_SERVER['REQUEST_URI'], '?random') !== false) {
        $random_post = get_posts(array(
            'numberposts' => 1,
            'orderby' => 'rand',
            'post_type' => 'post', 
        ));
         if (!empty($random_post)) {
            $random_post_id = $random_post[0]->ID;
            $random_post_url = get_permalink($random_post_id);
            wp_redirect($random_post_url);
            exit;
        }
    }
}
add_action('template_redirect', 'custom_redirect_on_parameter');

2. Once you done adding the function, just save the function.php file and reload the page of the site.

3. Now, whenever you or your visitors type “www.example.com/?random” in the URL, the system will automatically redirect you to a randomly selected post. It’s a fun and convenient way to explore your website’s content.

Conclusion:

We can use the WordPress hook for redirection to a Random Post URL. Redirection of URL to the random post is one of the convenient way to get the random post URL. As it will give ease to the person who wants to share the random post on social media without going into hassle of manually going to the posts and then copying the URL. You can go to the random URL link of the site to get better idea about it.