I'm overriding default WordPress gallery like so:

   add_filter( 'post_gallery', 'my_gallery_shortcode'), 12, 2 );

   function my_gallery_shortcode($output, $attr) {
         // some modifications to output here

         return $output;

Modifications to $output have average complexity, can't say that they take too much or too low processing time.

My question, should I cache $output via transients? If yes, what's the best way to get key for set_transient?

1 Answer 1


If you think your shortcode is hurting performance (measure and you will know!), then you might want to consider caching its output in a transient. A good way to get a unique key would be to consider what could differentiate calls to your shortcode function:

  1. its name
  2. the attributes passed
  3. the site URL (in cases where multiple site URLs are valid, e.g. a mobile domain name)

You also need to keep the key length short -- under 45 characters. What I find is good is to take an MD5 hash of the concatenation of those items, which gives you a nice short key that is highly unlikely to clash with another key.

$key = md5(__FUNCTION__ . serialize($attrs) . site_url());

A further thing to consider is setting an expiry on your transient. If you don't, the transient will be autoloaded with all other autoloaded options (transients are stored in the options table). This will increase memory use on every page, possibly hurting the performance of your site (oh, the ironing). If you are storing a lot of data in your transient, and it isn't needed on every page/post, don't autoload it! (i.e. set any expiry)

Of course, you have to consider that it might all be easier / more effective to use a caching plugin, which will cache much more than just what your function is generating. Weigh your options.

  • And another thing: the locale, e.g. when your content has been translated and may be presented in different languages using WPML or similar. Add . get_locale() to the string before calling md5().
    – webaware
    Nov 14, 2013 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.