
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.
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.
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.