WordPress Transient Naming

WordPress-Logo

Last week I went over how to use WordPress transients to cache data from an API call. I also talked about a problem where naming transients can be very difficult due to the size restriction of 40 characters. I also linked a great article on CSS Tricks by Scott Fennel that covers a lot about transients. What I failed to notice is that in that article Scott gave a fix for the naming problem.

What we are going to do is md5( … ) the GitHub repository and owner from the shortcode. MD5 has the ability to make almost any string into 32 characters – so we can use that to create a unique key easily with as much information as we want. That leaves us 8 characters leftover for the unique prefix which is important, because if we ever want to make a function that will purge all our transients we will want to have the same prefix so we can find them all extremely easily.

Once we add in the code our function will now look like this:

As you can see we have our prefix gtrd- and we then MD5 the owner and repository which will be enough to ensure that we get a unique README.md every time. Hopefully that is a more satisfactory solution to the problem then I presented in my previous article. I’ll also update my DobsonDev Shortcodes plugin to include this technique as well which should prevent the problem getting the same file when using the same cache_id (some people were using the version number as the cache_id so they had more than one with cache_id=”1.0″ which resulted in incorrect retrieval).

On a complete side note I learned that GitHub Gist‘s written in PHP don’t need to have the PHP tags for syntax highlighting. I don’t know if they changed this or what, but while in the editor there will be no highlighting unless you include the tags but once you save the Gist the highlighting will appear. This means all my subsequent PHP Gist’s from now on won’t include the tags so they should be a lot easier to copy paste for you all!

As always thank you for reading and please share it around as much as you can! Please feel free to put any suggestions or ideas for future tutorials in the comments section below.