Michael Gunner

Michael Gunner

© 2013 Michael Gunner. All rights reserved.

Random content PHP

Ever needed to display content randomly? Perhaps a random image, a random quote, or even a random WordPress post. There’s a very simple way to do this.

Create a PHP file where you will store or reference your content. You can reference images, text, whatever you like.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<? 
 //Chooses a random number 
 $num = Rand (1,4); 
 //Based on the random number, gives a quote 
 switch ($num)
 {
 case 1:
 echo "For me giving up is way harder than trying.";
 break;
 case 2:
 echo "Established in 1988.";
 break;
 case 3:
 echo "Don't change on me. Don't extort me unless you intend to do it forever.";
 break;
 case 4:
 echo "Be regular and orderly in your life, so that you may be violent and original in your work.";
 }
 ?>

Upload the file where your theme is. To reference it, just so a simple PHP include. This is easier to maintain then repeating the same code across multiple template files. You can see the above code in action in the footer of my site, the quotes are courtesy of rap legends Kanye West, Eminem and Tupac Shakur.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>