我构建了一个简单的插件,可以用来快速创建一个“漂亮的”自定义404页面,该页面位于WordPress页面区域中,可以轻松对其进行编辑。我最近发现,当Google网站管理员工具告知我软404数量有所增加时,我的插件未发送正确的404 not found标头。如您在下面的代码中看到的,我首先发送404 Not found标头,然后调用301永久重定向。
从概念上讲,我认为这应该可行(并且我已经在其他404插件中看到了此用法),但事实并非如此。可以显示404标头的唯一方法是,如果我在位置标头之后发送标头,但是这种方法无法达到目的,因为它显示空白页。我不太确定如何最好地在WordPress插件中实现此功能,并且我想确保可以在WordPress的页面结构中进行一些操作。
这里是功能:
if ($wp_query->is_404) {
$page_title = $this->options['404_page_title'];
$redirect_404_url = esc_url(get_permalink(get_page_by_title($page_title)));
header("HTTP/1.0 404 Not Found");
header("HTTP/1.1 301 Moved Permanently");
header("Location:" . $redirect_404_url);
die;
}
而不是重定向到404页面,而是发送404标头并仅打印出404页面内容。
未经测试,但想法是这样的...
<?php
if ($wp_query->is_404) {
header("HTTP/1.0 404 Not Found");
$page_title = $this->options['404_page_title'];
// Override the current post to the 404 page
$GLOBALS['post'] = get_page_by_title($page_title);
}
我终于明白了!感谢布雷迪帮助我指出正确的方向!
首先,我设置了一个函数,以在404错误时重定向到插件创建的页面。然后,我创建了另一个函数,如果页面标题与插件创建的404页面的页面标题匹配,则会向页面添加404标头状态。最后,我将函数连接到构造函数中。小菜一碟。 :)
404重定向功能:
public function redirect_404() {
global $options, $wp_query;
if ($wp_query->is_404) {
$page_title = $this->options['404_page_title'];
$redirect_404_url = esc_url(get_permalink(get_page_by_title($page_title)));
wp_redirect($redirect_404_url);
add_action('wp', array(&$this, 'redirection'));
exit();
}
}
将404页眉应用于页面功能:
public function is_page_function() {
global $options;
$page_title = $this->options['404_page_title'];
if (is_page($page_title)) {
header("Status: 404 Not Found");
}
}
动作:
add_action('template_redirect', array( &$this, 'redirect_404' ), 0);
add_action('template_redirect', array( &$this, 'is_page_function'), 0);