How to Have Yoast SEO's XML Sitemap Register Images Served from a Content Delivery Network

If you're serving your site's images from a CDN, this snippet tells Yoast SEO to register the CDN versions in its sitemap.

Posted by David Coleman on May 9, 2018

If you're having trouble getting your images indexed by Google and you're using the combination of a CDN (content delivery network) and Yoast SEO on Wordpress, it might be because Yoast SEO's sitemap is pointing to the non-CDN versions, while Google can only see the CDN versions mentioned on your site.

But it's very easy to fix. Add this snippet to your functions.php file, replacing the MYDOMAIN.com and CDN.MYDOMAIN.com sections with whatever matches your setup.

// Telling Yoast XML Sitemap to redirect images to CDN versions
function wpseo_cdn_filter( $uri ) {
    return str_replace( '//MYDOMAIN.com', '//CDN.MYDOMAIN.com', $uri );
}
add_filter( 'wpseo_xml_sitemap_img_src', 'wpseo_cdn_filter' );

When the XML sitemap is regenerated, it should now point the image files to the CDN versions.

It then can take a while for Google to pick up on the change and start indexing your images--it doesn't usually happen overnight.

Extra Tip: Add CDN to Search Console

Google also recommends that you add the CDN's subdomain to your Search Console properties so that they can alert you to any crawling errors they come across there.