How to use transients and variables

I am trying to implement transient fragments, I’ve been doing what is suggested here: http://css-tricks.com/wordpress-fragment-caching-revisited/

While it is working for headers, footers, landing pages, I am having issues making it work for those sections that include variables.

This is my code in functions.php:

function fragment_cache($key, $ttl, $function) {
  if ( is_user_logged_in() ) {
    call_user_func($function);
    return;
  }
  $key = apply_filters('fragment_cache_prefix', 'fragment_cache_').$key;
  $output = get_transient($key);
  if ( empty($output) ) {
    ob_start();
    call_user_func($function);
    $output = ob_get_clean();
    set_transient($key, $output, $ttl);
  }
  echo $output;
}

And here is a simplified version of my code on a single page (I’m using Advanced Custom Fieds repeaters, but it’s no concern to this issue I think):

while ( have_rows('images') ): the_row();
  fragment_cache('cms_images_text' . $post->ID, WEEK_IN_SECONDS, function() {
    $gallery_image = get_sub_field('image');
    $gallery_image_small = $gallery_image['sizes']['square-small'];
    echo '<img src="' . $gallery_image_small .  '">;
  });
endwhile;

My issue is that within this while loop, I get returned four identical images. How can I get this solved?

1 Answer
1

You’re saving the data in a loop under the same key for each iteration. You’ll have to add the index of the current iteration of the loop to the key if you want a unique value for each. Something like:

$i = 0;
while ( have_rows('images') ): the_row();
  fragment_cache('cms_images_text_' . $i . '_' . $post->ID, WEEK_IN_SECONDS, function() {
    $gallery_image = get_sub_field('image');
    $gallery_image_small = $gallery_image['sizes']['square-small'];
    echo '<img src="' . $gallery_image_small .  '">';
  });
  $i++;
endwhile;

Or perhaps just save the entire loop’s contents under a single key.

Leave a Comment