2

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?

  • Where does $gallery_image come from? Also: Please do not delete and repost questions. This will get you banned. Thank you. – kaiser Feb 2 '15 at 17:27
  • It comes from an Advanced Custom Field, I didn't add the whole code here – alemur Feb 2 '15 at 17:28
  • Can you confirm that you have read and understood the second part of my last comment? Also: Can you confirm that ACF isn't the problem? – kaiser Feb 2 '15 at 17:29
  • 2
    Please file an edit and show us how the cache connects to your snippet. It's very unclear and not reproducible. – kaiser Feb 2 '15 at 17:32
  • 2
    @Akmur the function fragment_cache() is defined, but never used in the code we can see... to help you we need to know where and how you are using it. – gmazzap Feb 2 '15 at 17:41
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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