PHP Random String From Array In WordPress

When I struggle to find a clear answer to something and eventually come up with something that works, I like to repost it here so others can hopefully save themselves some time. This is one of those times.

If you want to display a random string from an array in WordPress, such as a random quote from a collection of your favourites, I’m going to show you how. Note that this isn’t a WordPress-specific solution, but I like WordPress and I like when you do too so I’m going to assume you’re using it*.

Open up your functions.php file and add in the following code:

The array $quotes is where we’re going to store all our quotes, so feel free to just replace my Adventure Time quotes above with your own. As always, you should replace the namespace_ part with your theme/plugin’s.

Now when you’d like to output the random quote somewhere in your theme, just use the following:

Why not make a shortcode out of it too?

Have fun surprising your users with all that randomeness!

*And let’s be serious: If you’re not using WordPress, you’ll most likely have no problem figuring out what to do.