Tuesday, September 10, 2013

Randomly Rotate Strings for Display on a WordPress Page Using PHP (Shortcode Exec)

I was asked by our marketing team if we could have our WordPress-based homepage randomly display one of several possible tag lines. Well, sure... with PHP it's dead simple. And if you have Shortcode Exec PHP installed in your WordPress site, it's actually even easy under WordPress.

Here's how I did our particular page. It will randomly choose a string from a PHP array, and present it in a clean looking, rounded-corner wrapper. If you use this, of course you may want to modify the strings and styles to suit your needs. Note, rounded corners aren't fully supported by most IE versions ~ I try not to waste time developing for IE, but if you have a solution, feel free to post it here.

Create a new Shortcode Exec PHP like so...
/* Rotate random hyperbole lines on the homepage */
$hyperboleStrings = array(
1  => "We have the best product",
2  => "Our solution solves problems",
3  => "Industry leading solutions"
);
$whichStringToShow = rand(1, sizeOf($hyperboleStrings));
echo $hyperboleStrings[$whichStringToShow];
Now all you have to do is save it and go to the page you want to add it to. In my case, I had to go to Appearance -> Editor -> header.php...
<div class="rounded_corners" id="hyperbole-line">
<?php echo do_shortcode("[homepage_hyperbole_rotator]"); ?>
</div>
And, here's my CSS...
.rounded_corners {
-moz-border-radius: 10px; /* firefox */
-webkit-border-radius: 10px; /* safari, chrome */
-khtml-border-radius: 10px; /* KDE HTML layout engines */
border-radius: 10px; /* css3 */
}
#hyperbole-line {
background-color: #20b0b0;
width: 85%;
padding: .25em;
text-align: center;
margin: 10px auto 10px auto;
color: #fff;
font-style: italic;
font-size: 1.75em;
padding: 0;
letter-spacing: 1px;
}

No comments:

Post a Comment