1

I have a ton of hardcoded images and a bunch of custom image sizes. All image URLs within the content of the posts link to the full-size image. I tried a string replace on the_content filter adding the -300x200.jpg, and this reduced my page size by half, but the load time is hellacious, so it's not worth it. Is there a better way? I looked into wp_get_attachment_image_src but can't seem to get it to do anything at all. If it helps, all the images are attached to the post. Thanks heaps!

function replace_image_url($text) {
if (is_category(‘my-cat’)){
$text = str_replace('.jpg', ‘-300x200.jpg’, $text);
return $text; 
} 
else return $text;
}
add_filter('the_content', 'replace_image_url');

The following is a much better solution, but incomplete, as there are multiple images in the content, and while it replaces the source image with the medium image (whatever size it is), it replaces all images with the first attached image. How do I get this to apply to all images with their respective medium attachment urls?

add_filter( 'the_content', 'FilterImages', 0 );
function FilterImages( $content )
{
$image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium');  
$image = (isset($image[0])) ? $image[0] : ''; 
$content = str_replace('src=', 'src="'.$image.'"', $content);


  return $content;
}
  • Is the load time hellacious because of the sheer volume of the smaller images loading all at once? you could look into lazy-loading solutions, where images only load once they're in the browser window. There are a lot of random plugins that do this. e.g. luis-almeida.github.io/unveil – Taruc Mar 5 at 0:04
  • Thanks for your reply! It's actually faster with the original images without the string replace function. It's the string replace function that's taking up all the time, even more time than loading a site twice the size with large images -- that's the only difference. I'm desperately trying to find a solution, any solution! I just want these images to pick up something smaller, the smaller versions have already been saved, just not sure how to get the url to recognize them. – alice Mar 5 at 0:08
  • And yes, already using lazy loaded, but the original image is being pulled when it should be pulling a smaller image as the full images are just way too big. – alice Mar 5 at 0:09
  • Got it; thanks. Would you post the php? Maybe calling the intended side images might help rather than using the str_replace method. Or if you wanna "cheese" through the issue, a simple page cache would probably make it go away. I like KeyCDN's Cache Enabler. – Taruc Mar 5 at 4:43
  • Hi thanks for having a lookover. We are using CDN cache and that helps but it still could be faster. Will post an edit with the php. How do you call the side images dynamically? – alice Mar 5 at 15:16

Your Answer

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

Browse other questions tagged or ask your own question.