Switching gallery / attachment image srcs to a static domain / CDN in WordPress

For the majority of sites that I manage, I use a www. subdomain as the main URL, which dynamic pages are served from. For static assets, such as images, javascript, CSS, etc. I use a static subdomain. This makes it easy to send long expires headers for everything on the static subdomain, and keep cookies restricted to the www subdomain only, resulting in a faster website.

Normally I write my posts in HTML, meaning I explicitly set the src of any images included in the post to point to the static subdomain. However, I realised today that on one of my sites I’m using the [gallery] shortcode. With this WordPress automatically creates an image gallery based on the images added as attachments to the post, and of course, will just use the standard www. subdomain for the image srcs.

Thankfully, you can filter the src that WordPress uses for attachment images very easily. In my theme’s functions.php, I added the following:

add_filter('wp_get_attachment_image_src', 'staticize_attachment_src', null, 4);
* @param array|false  $image         Either array with src, width & height, icon src, or false.
* @param int          $attachment_id Image attachment ID.
* @param string|array $size          Registered image size to retrieve the source for or a flat
*                                    array of height and width dimensions. Default 'thumbnail'.
* @param bool         $icon          Whether the image should be treated as an icon. Default false.
function staticize_attachment_src($image, $attachment_id, $size, $icon)
	if (is_array($image) && !empty($image[0])) {
		$image[0] = str_replace('http://www.', 'http://static1.', $image[0]);
	return $image;

You need to hook into the wp_get_attachment_image_src action. The callback has 4 paramaters – the first is the important one in our case, $image. This is a numerically indexed array, with index 0 being the src of the image. So you can just do a find and replace on the src in the callback to replace the default subdomain with your static subdomain.

Bear in mind that if your site uses / allows HTTPS, then you’ll need to modify the code above appropriately.

Posted on by xoogu, last updated

Leave a Reply