如何在Automattic AMP插件中清理ACF WYSIWYG内容并转换图片标签
我刚好处理过和你完全一样的场景——用ACF灵活内容的WYSIWYG字段搭建自定义页面/CPT,AMP插件自动处理the_content但漏掉了ACF字段的内容。给你几个亲测有效的解决方案,按优先级推荐:
方案1:全局处理所有ACF WYSIWYG字段(最省心)
利用ACF针对字段类型的过滤器,自动在AMP页面把WYSIWYG内容转换成AMP兼容格式,直接调用AMP插件官方的转换函数,比自己写正则靠谱太多:
add_filter('acf/format_value/type=wysiwyg', 'convert_acf_wysiwyg_to_amp', 10, 3); function convert_acf_wysiwyg_to_amp($value, $post_id, $field) { // 只在AMP页面生效,避免影响非AMP页面 if (function_exists('is_amp_endpoint') && is_amp_endpoint()) { // 调用AMP插件自带的内容转换函数,自动处理img→amp-img、iframe→amp-iframe等 if (function_exists('amp_convert_content')) { $value = amp_convert_content($value); } } return $value; }
把这段代码放到你的自定义子主题functions.php里就行,它会自动作用于所有ACF的WYSIWYG字段,不仅转图片,还会处理其他不符合AMP标准的标签,比如把普通iframe转成amp-iframe。
方案2:针对特定灵活内容布局处理(更灵活)
如果你不想全局处理所有WYSIWYG字段,只想针对灵活内容里的特定布局做转换,可以在模板输出字段时手动处理:
// 假设你的灵活内容字段名为flexible_content_field if (have_rows('flexible_content_field')) { while (have_rows('flexible_content_field')) { the_row(); // 假设你的WYSIWYG布局名为wysiwyg_section if (get_row_layout() == 'wysiwyg_section') { $wysiwyg_content = get_sub_field('your_wysiwyg_subfield_name'); // 只在AMP页面做转换 if (function_exists('is_amp_endpoint') && is_amp_endpoint()) { if (function_exists('amp_convert_content')) { $wysiwyg_content = amp_convert_content($wysiwyg_content); } } echo $wysiwyg_content; } // 其他灵活内容布局的处理... } }
这个方式适合你有多个WYSIWYG字段,但只需要处理其中一部分的场景。
方案3:自定义正则替换(不推荐,仅作备选)
如果因为某些原因无法使用AMP插件的官方转换函数(比如旧版本插件),可以自己写正则替换img标签为amp-img,但要注意AMP要求amp-img必须有width和height属性,所以需要额外处理图片尺寸:
function convert_img_to_ampimg($content) { // 非AMP页面直接返回原内容 if (!function_exists('is_amp_endpoint') || !is_amp_endpoint()) { return $content; } // 先替换基本结构 $pattern = '/<img(.*?)src=["\'](.*?)["\'](.*?)>/i'; $replacement = '<amp-img$1src="$2"$3layout="responsive"></amp-img>'; $content = preg_replace($pattern, $replacement, $content); // 给没有width/height的amp-img添加尺寸(通过获取图片本身的尺寸) $content = preg_replace_callback('/<amp-img(.*?)src=["\'](.*?)["\'](.*?)>/i', function($matches) { $src = $matches[2]; // 获取图片的原始尺寸 $image_size = getimagesize($src); if ($image_size) { $width = $image_size[0]; $height = $image_size[1]; return "<amp-img{$matches[1]}src=\"{$src}\" width=\"{$width}\" height=\"{$height}\"{$matches[3]}layout=\"responsive\"></amp-img>"; } // 如果获取不到尺寸,就返回原标签(可能会触发AMP验证错误) return $matches[0]; }, $content); return $content; } // 绑定到ACF WYSIWYG字段的过滤器 add_filter('acf/format_value/type=wysiwyg', 'convert_img_to_ampimg', 10, 3);
⚠️ 注意:这个方案需要处理很多边缘情况(比如外部图片无法获取尺寸、图片属性缺失等),容易触发AMP验证错误,所以优先推荐前两个方案。
最后提醒
- 确保你的AMP for WordPress插件是最新版本,
amp_convert_content函数是官方维护的,兼容性最好。 - 转换完成后,用Google的AMP验证工具检查页面,确保没有验证错误。
内容的提问来源于stack exchange,提问作者kevinkonrad
相关产品推荐
相关产品推荐

