如何在WordPress中设置单个模板不在AMP模式下加载?
解决指定模板禁用AMP的方案
使用AMP官方插件时,可通过以下代码在主题的functions.php中实现指定模板禁用AMP:
方法一:针对页面/文章关联的模板
添加以下代码,替换其中的模板文件名即可:
add_filter( 'amp_post_template_enabled', 'exclude_specific_template_from_amp', 10, 2 ); function exclude_specific_template_from_amp( $enabled, $post ) { // 替换为你要排除的模板文件名(如template-special.php) $excluded_template = 'template-custom.php'; $current_template = get_page_template_slug( $post->ID ); if ( $current_template === $excluded_template ) { return false; } return $enabled; }
方法二:全局匹配模板文件
如果需要直接针对模板文件本身(不管它被哪个页面使用),可以用这个代码:
add_filter( 'amp_enabled', 'exclude_template_from_amp_global' ); function exclude_template_from_amp_global( $enabled ) { global $template; // 替换为目标模板文件名 if ( basename( $template ) === 'template-custom.php' ) { return false; } return $enabled; }
排查之前修改失败的常见原因
- 文件名错误:确保填写的是主题目录中实际的模板文件名,不要遗漏
.php后缀 - 钩子优先级问题:可尝试将代码中的优先级数值(如10)改为更高的数字(如20),确保你的代码能覆盖默认设置
- 缓存干扰:修改代码后清空网站缓存和浏览器缓存,再进行测试
验证是否生效:打开使用目标模板的页面,查看源代码,若没有<html amp>或<html ⚡>标签,即说明AMP已被成功禁用。
内容的提问来源于stack exchange,提问作者RicardoRuizQ
相关产品推荐
相关产品推荐

