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;
}