Random Item from CMS Database

There are few ways to do this in WordPress CMS using the PHP web language. What I would say the “best way” involves editing either original or Child Theme functions.php file. Therefore it is bit risky and you could potentially take your side down in an event of an incorrect implementation. Let’s look at the fool safe “easy way” first.

By creating a page template

The advantage of this method is that we are not editing your original or Child PHP theme files. Instead, a separate PHP file is created (either directly on the server or outside then uploaded using FTP) as a template file. This may also potentially create coding conflicts but usually can be resolved by simply removing the newly created file from the server. This new template must be located in the templates folder of your WordPress theme files. Hence the location should be the same as the page.php file location. Usually it is in “themes” folder.

First, create a PHP file with a desired name. Let’s call this file “template-random.php” in this particular example.

<?php
/* Template Name: Random Item */
query_posts(array('orderby' => 'rand', 'showposts' => 1));
 if (have_posts()) :
   while (have_posts()) : the_post(); ?>
     <h1><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h1>
     <?php the_content(); ?>
   <?php endwhile;
 endif; ?>

After creating the template go to the Admin Panel of your WordPress and create a new page (let’s call it “random”). Choose the template we just uploaded as the template of the page. The template we just created should appear on the list of selectable templates under “Attributes” pane as “Random Item”. A random page/post will be generated every time this new random page is generated. For example, sanuja.com/blog/random will give you a random item from the database. Now you can use “a href” type links or buttons to direct users to random pages.

By updating the functions.php

Update the functions file in your main theme files or Child Theme files with the following code.

function le_random_post() {
if ( isset( $_GET['random'] ) && $_GET['random'] == 1 ) {
   $posts = get_posts( 'post_type=post&orderby=rand&numberposts=1' );
      foreach( $posts as $post ) {
      $link = get_permalink( $post );
      }
      wp_redirect( $link,307 );
   exit;
       }
}
add_action( 'template_redirect','le_random_post' );

Now you are done! Just use the appropriate URL to generate items from this script. For example, this will generate a random item as soon as the URL, https://sanuja.com/blog/?random=1 is requested.