Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

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.

share|improve this answer
    
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 '13 at 9:54
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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