I want to filter the src URL of every image (every img
tag) on all of my WordPress pages, with the goal of adding a query string to the end of the image URL. (The reasons why are outside the scope of my question here).
My understanding is that I should be able to use the wp_get_attachment_image_src filter to achieve this goal.
I found this example filter which is supposed to do the trick:
function change_src($image, $attachment_id, $size, $icon)
{
$image[0] .= '?ver=123';
return $image;
}
add_filter('wp_get_attachment_image_src', 'change_src', 10, 4);
And there is another function provided at Change Image URL to a CDN which is also supposed to achieve this.
However, when I test either of these two functions on my site, it only changes the src
URL of each of my pages’ featured images. It does not change the URL of any of the other images on my pages. The other images were all added using the Add Media button in the editor, and my assumption is that all of them should be affected by this filter.
My questions are:
-
Is it expected behaviour that the
wp_get_attachment_image_src
filter only affects the featured image of a page, and not the images in the page content which have been added via the Add Media button? -
If it’s not expected behaviour, then what might be causing this filter not to work on the other images on my site?
-
If it is expected behaviour, then can you suggest an alternative function that would work on all of my images? Note that I’d prefer to use a proper WordPress filter to achieve this, rather than some kind of search and replace on the page contents.
Also, I’m aware that I need to use the wp_calculate_image_srcset
filter to change the URL of the images inside the srcset
part of the img tag. I’ve tested that using the function given at Change Image URL to a CDN and that actually does work correctly on all of the images on my pages. So it’s all the more puzzling to me that wp_calculate_image_srcset
works on all my images, but wp_get_attachment_image_src
does not.
I hope someone can point me in the right direction!