After a site has been running for a long time, 404 pages are almost unavoidable. They leave a bad impression on users and hurt the user experience. If we can discover those 404 pages quickly and fix them right away, the site feels more reliable to users and it also helps improve SEO. The code below emails the site administrator when WordPress encounters a 404 page.
// 网站信息
$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(
, , $string);
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
return $string;
}
$message =
TIME: . $time .
.
*404: . $request .
.
SITE: . $site .
.
THEME: . $theme .
.
REFERRER: . $referer .
.
QUERY STRING: . $string .
.
REMOTE ADDRESS: . $address .
.
REMOTE IDENTITY: . $remote .
.
USER AGENT: . $agent .
;
// 最后通过邮件发送404页面通知信息
mail($email, 404 警告: . $blog . [ . $theme . ], $message, From: $email);
Paste the code above into WordPress functions.php. When the site returns a 404 page, the administrator will receive an email alert immediately and can start fixing the problem right away.
