The snippet should be saved as a PHP template for pages and a page has to use it.
Step 1. Create a new file random.php inside your active theme folder and put the following code inside it:
<?php /* Template Name: random */ ?> <?php $rand_post=get_posts('numberposts=1&orderby=rand'); foreach($rand_post as $post) : ?> <script> location="<?php the_permalink(); ?>";</script> <?php endforeach; ?>
Step 2. Login to the WordPress dashboard, select the page on which you want to display random posts, and select the “random” template for it.