WordPress CDN 全局媒体网址

近期研发小程序遇到的问题是,W3 Total Cache 的 CDN 配置无法延伸至Rest API里面。WP Rest API 给到的 JSON 里面的媒体没有改变成CDN网址。 这里我们使用的是回源性质的CDN,所以需要保留原网域的媒体网址,但在wordpress template或API JSON里提供到的网址全部变成CDN网址:
global $DOMAIN_ORIGINAL;
global $DOMAIN_CDN;

$DOMAIN_ORIGINAL = 'https://domain.com';
$DOMAIN_CDN = 'https://cdn.domain.com';

# 额外
function cdn_attachments_urls($url, $post_id)
{
  global $DOMAIN_ORIGINAL;
  global $DOMAIN_CDN;
  
  return str_replace($DOMAIN_ORIGINAL.'/wp-content/uploads', $DOMAIN_CDN.'/wp-content/uploads', $url);
}
add_filter('wp_get_attachment_url', 'cdn_attachments_urls', 10, 2);
额外附上 ACF 的 CDN 媒体网址更改:
global $DOMAIN_ORIGINAL;
global $DOMAIN_CDN;

$DOMAIN_ORIGINAL = 'https://domain.com';
$DOMAIN_CDN = 'https://cdn.domain.com';

# ACF
function fz_acf_format_value( $value, $post_id, $field )
{
  global $DOMAIN_ORIGINAL;
  global $DOMAIN_CDN;

    if(is_array($value))
    {
        $value['url'] = str_replace($DOMAIN_ORIGINAL.'/wp-content/uploads', $DOMAIN_CDN.'/wp-content/uploads', $value['url']);
        if(isset($value['sizes']) && !empty($value['sizes'])){
            foreach($value['sizes'] as $key=>$size){
                $value['sizes'][$key] = str_replace($DOMAIN_ORIGINAL.'/wp-content/uploads', $DOMAIN_CDN.'/wp-content/uploads', $size);
            }
        }
    }else{
        $value = str_replace($DOMAIN_ORIGINAL.'/wp-content/uploads', $DOMAIN_CDN.'/wp-content/uploads', $value);    
    }
  return $value;
}
add_filter('acf/format_value/type=image', 'fz_acf_format_value', 9999,9999);
add_filter('acf/format_value/type=file', 'fz_acf_format_value', 9999,9999);
本文由 Felicoz https://felicoz.com/ 原创发布,转载请保留地址!
cdn wordpress