wordpress排查404模板未生效
问题背景
function get_404_template($template){
unset($template);
return TPL . '/tpl.404.php';
}
add_filter('404_template', 'get_404_template', 10, 1);
在访问不存在的文章或页面时,走了服务器原生的报错
Sorry for the inconvenience. Please report this message and include the following information to us. Thank you very much! URL: https://yangjunwei.com/123.html Server: XXXX Date: 2026/01/24 11:10:14 Powered by Tengine
理论上应该走上述 tpl.404.php 的模板。
分析解决
WordPress 404 模板未生效,而是返回 Tengine 原生报错,首先要排除服务器层面(Nginx/Tengine)优先拦截了 404 请求,未将请求传递到 WordPress 的 PHP 处理流程中,导致 WordPress 的 404_template 钩子没有触发。
1. 服务器端(Nginx/Tengine)配置调整
检查 wordpress 站点 Nginx/Tengine 配置中 location / 块,确保包含 WordPress 的 rewrite 规则,且关闭原生的 404 截断逻辑,需确保 404 请求能传到 WordPress 的 index.php 处理。
server {
listen 80;
listen 443 ssl;
server_name yangjunwei.com;
root /站点根目录;
index index.php index.html;
# SSL 配置省略...
location / {
# 核心:WordPress固定链接重写规则,确保所有请求先走index.php
try_files $uri $uri/ /index.php?$args;
# 禁用服务器原生404拦截(关键)
# error_page 404 = /index.php;
# error_page 404 /404.html;
}
......
}
如有修改,记得重启 Nginx/Tengine。
2. WordPress 代码层面
确保 404_template 文件路径正确且优先级足够
function get_404_template($template) {
unset($template);
$custom_404 = TPL . '/tpl.404.php';
// 检查模板文件是否存在,避免报错
if (file_exists($custom_404)) {
$template = $custom_404;
}
return $template;
}
// 提高优先级(比如20),确保覆盖默认逻辑
add_filter('404_template', 'haibor_get_404_template', 20, 1);
总结一下:首先确保服务器把 404 请求交给 WordPress 处理,再通过 WordPress 钩子指定自定义 404 模板,最后确保 WordPress 正确处理 404 状态即可。