1

I want caching all images on my site and prevent the browser download the images all times, so I would like add an version query tag to all images (for example: ?v=20160505)

How can I add this for image urls? Now I use this code to show images in my theme:

echo get_the_post_thumbnail( $thumbnail->ID, 'thumbnail' );
2
  • 2
    May I ask why? A image is not dinamic by definition.
    – cybmeta
    May 5, 2016 at 21:41
  • @cybmeta, extremely rare but might happen (delete image, upload another under the same name. IIRC edit image can also cause that) May 6, 2016 at 8:52

1 Answer 1

6

Don't know why you want to do it when there's update_post_thumbnail_cache() in WordPress and set expire headers on server side. But you can try this in your functions.php:

add_filter('wp_get_attachment_image_src', function($img, $id, $size, $icon) {
  
    $img[0] = $img[0] . '?v={$some_version}';

    return $img;
    
}, PHP_INT_MAX, 4);
2
  • 2
    +1 but probably better to use file modification time than hardcoding a version number May 6, 2016 at 8:54
  • You want to do it because browsers cache images. If the version or attribute changes, the browser will update the image. This is quite handy if you have uploaded a new version with the same filename.
    – Trond
    Feb 2, 2022 at 9:00

Your Answer

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

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