How to configure sitemap and og:image meta links on Yoast WordPress-SEO to be served through your CDN

The Yoast WordPress-SEO is a great plugin for getting SEO on your blog in an easy to use, and easy to manage function.

Recently I encountered an issue where the <meta> og:image links were not being served over our CDN, and were referencing their original image locations. og:image meta tags are used by Facebook and Twitter to give users the various thumbnail options when they create a post in Facebook that includes the link to a site/page/post.

The fix for this was not easy, and I ended up talking with some of the developers on Github in order to figure it out. Fortunately, they’ve created a general wpseo_og_ filter to use, although figuring out how to use it can be difficult.

Without further ado, here is the code you need in order to fix your og:image and sitemap image links to use your CDN:

// Declare noncdn and CDN domains for the SEO Filters
$noncdn_domains = array('www.yourdomain.com', 'yourdomain.wpengine.com', 'staging.yourdomain.com');
$cdn_domain = 'cdn.domain.com';

/*
 * Change Yoast wordpress image URLs for the sitemap to point to the CDN
*/

function wpseo_sitemap_cdn_filter( $uri ) {
  global $cdn_domain;
  global $noncdn_domains;
  return str_replace($noncdn_domains, $cdn_domain, $uri );
}

add_filter( 'wpseo_xml_sitemap_img_src', 'wpseo_sitemap_cdn_filter' );

/*
* Ensure that og:image Facebook links are served through the CDN
*/

function wd_alter_og_image($val){
  global $cdn_domain;
  global $noncdn_domains;
  return str_replace($noncdn_domains, $cdn_domain, $val );
}
add_filter('wpseo_og_og_image', 'wd_alter_og_image');

That’s it! Then it works.