一个网站运行时间长了,难免会出现 404 页面,404 页面会给用户留下不好的印象,影响用户体验,如果我们能及时发现 404 页面,并很快修复,用户就会觉得我们的网站很靠谱,同时也有助于提升网站的 SEO 友好度。下面的代码可以在 WordPress 出现 404 页面时,通过邮件通知网站管理员。
// 网站信息
$blog = get_bloginfo('name');
$site = get_bloginfo('url') . '/';
$email = get_bloginfo('admin_email');
// 主题信息
if (!empty($_COOKIE[nkthemeswitch . COOKIEHASH])) {
$theme = clean($_COOKIE[nkthemeswitch . COOKIEHASH]);
} else {
$theme_data = wp_get_theme();
$theme = clean($theme_data->Name);
}
// 来源网址
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = clean($_SERVER['HTTP_REFERER']);
} else {
$referer = undefined;
}
// 请求 URI
if (isset($_SERVER['REQUEST_URI']) && isset($_SERVER[HTTP_HOST])) {
$request = clean('http://' . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI]);
} else {
$request = undefined;
}
// 请求字符串
if (isset($_SERVER['QUERY_STRING'])) {
$string = clean($_SERVER['QUERY_STRING']);
} else {
$string = undefined;
}
// 用户的IP 地址
if (isset($_SERVER['REMOTE_ADDR'])) {
$address = clean($_SERVER['REMOTE_ADDR']);
} else {
$address = undefined;
}
// user agent
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$agent = clean($_SERVER['HTTP_USER_AGENT']);
} else {
$agent = undefined;
}
// 用户识别码
if (isset($_SERVER['REMOTE_IDENT'])) {
$remote = clean($_SERVER['REMOTE_IDENT']);
} else {
$remote = undefined;
}
// 记录时间
$time = clean(date(F jS Y, h:ia, time()));
// 净化数据
function clean($string) {
$string = rtrim($string);
$string = ltrim($string);
$string = htmlentities($string, ENT_QUOTES);
$string = str_replace(\n, , $string);
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
return $string;
}
$message =
TIME: . $time . \n .
*404: . $request . \n .
SITE: . $site . \n .
THEME: . $theme . \n .
REFERRER: . $referer . \n .
QUERY STRING: . $string . \n .
REMOTE ADDRESS: . $address . \n .
REMOTE IDENTITY: . $remote . \n .
USER AGENT: . $agent . \n\n\n;
// 最后通过邮件发送404页面通知信息
mail($email, 404 警告: . $blog . [ . $theme . ], $message, From: $email);
把上面的代码粘贴到 WordPress 的 functions.php 中,网站出现 404 页面的时候管理员就可以马上收到通知邮件,然后立即着手修复。