I was looking for a plugin or some code to shuffle headlines on our home page at DK New Media to have some fun and dress up the home page a bit. The problem was that I have a theme applied that has specific fields for the tag line and description of the site, and I didn’t feel like tearing it apart for this modification.
To do this with plugins and theme modifications would require of use the fantastic Advanced Custom Fields plugin with the Repeater Field Add-on – this is how we’d do it for clients. For our site, though, we often take shortcuts and this little code snippet works just as well!
Basically, you just enter as many headlines into a field and separate them with some character (I use the “|” symbol). Then you can utilize PHP’s explode function which puts all the headlines into an array and then use PHP’s shuffle function to shuffle the order of the array, and then display the first result. You only display the first result… this way if you only have one result it will still be displayed properly!
In our theme where the headline is displayed, we just replace the headline text with the following code:
<?php $headlines = explode('|',trim(get_field('headline_text'));
$headlines = shuffle($headlines);
echo $headlines; ?>
If you want to get fancy, you can pass this as a custom variable in Google Analytics and actually test which headlines perform the best!