Someone recently asked me to add some testimonials to their website. They had a collection of quotes from their customers and wanted one to be displayed on each page at random. Although this post it titled how to show random ‘quotes’ in WordPress the concept can be applied to pretty much anything and is not limited to quotes. It also not limited to WordPress as we’re just going to be using some simple PHP.
There are several ways we can do this, we’ll look at a very simple method using the array_rand function.
First of determine how the quotes are to be displayed. I’m going to be outputting a quote with a citation following it, like this:
“I see little commercial potential for the internet for the next 10 years.”
- Bill Gates, 1994
We’ll put the quotes into variables:
$quote1 = ‘We are much better at writing code than haikus.’;
We could put the citation in this variable too and then explode the variable later but for simplicity we’ll put the citation into another variable.
$quote1_cite = ‘Matt Mullenweg’;
We can then repeat this for as many quote as we have. We’re just going to write this out, but had a lot of quotes or if you were feeling adventurous/efficient you could produce these variable programmatically.
$quote2 = ‘Getting information off the Internet is like taking a drink from a fire hydrant.’;
$quote2_cite = ‘Mitchel Kapour’;
$quote3 = ‘Having nothing, nothing can he lose. ‘;
$quote3_cite = ‘William Shakespeare’;
Now we’ve got our quotes and citations we’ll put them into an array as key => value pairs.
$quote_array = array(
$quote1 => $quote1_cite,
$quote2 => $quote2_cite,
$quote3 => $quote3_cite,
(See here for the 5.4 array syntax)
Now we’ve got an array full of quotes all we need to do is randomly selet one using array_rand.
$random_quote = array_rand($quote_array);
Now we’ve got the quote in the $random_quote variable we can get the corresponding citation with this:
$random_quote_cite = $quote_array[$random_quote];
We can now echo out the variables wherever we want on our page.
The full code is this:
$quote1_cite, $quote2 => $quote2_cite, $quote3 => $quote3_cite, ); $random_quote = array_rand($quote_array); $random_quote_cite = $quote_array[$random_quote]; ?>""""
Try refreshing the page, the quote below is using the above code…