Home » PHP Random String From Array In WordPress

PHP Random String From Array In WordPress

1 year ago

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.


  • http://www.facebook.com/rob.blank.52 Rob Blank

    I tried the php input method and it didn’t work. When I switched from visual to text editor, the whole line disappeared.

    • bryceadams

      You cannot add this to a page using the normal editor in WordPress, unless you have a plugin that ALLOWS PHP in posts/pages.

      Manually inserting it in your functions.php folder is what you need to do. You can also insert the shortcode code and then you’ll be able to use the shortcode in the editor on a post or page with no problems.

  • Karsten Tietje

    Just what i was looking for, thx! Is there anyway i can cycle through the quotes with a fade animation without refreshing the page?

    • bryceadams

      Nope, not with this. Look into a ‘jquery’ solution.