连接到 send_headers 时 WordPress 发送 404
WordPress sending 404 when hooking into send_headers
我正在尝试连接到 WordPress 的 send_headers
功能,以便检查是否请求了 sitemap.xml
。这样,我就可以提供自定义 PHP 函数,以根据 WordPress 帖子和页面自动生成 XML。
add_action( 'send_headers', 'custom_send_headers');
if( !function_exists('custom_send_headers') ) :
function custom_send_headers( )
{
global $route, $wp_query, $window_title;
$bits = explode( "/", $_SERVER['REQUEST_URI'] );
if( $bits[1] === 'sitemap.xml' )
{
if ( $wp_query->is_404 ) {
$wp_query->is_404 = false;
}
include('sitemap.php');
die();
}
}
endif;
一切正常,我的 PHP 文件包含适当的 headers:
<?php header('Content-Type: application/xml'); ?>
<?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
....
</urlset>
为什么 WordPress 会发送 404?
我尝试使用 WordPress 模板,但似乎不起作用。
$template = locate_template('sitemap.php');
load_template($template);
还有其他我应该挂钩的功能吗?我是否错过了我应该做的其他事情?
您可能仍需要发送 200 OK
header,因为您正在绕过发送内容的正常方法。
在 include('sitemap.php');
之前添加 header("HTTP/1.1 200 OK");
我正在尝试连接到 WordPress 的 send_headers
功能,以便检查是否请求了 sitemap.xml
。这样,我就可以提供自定义 PHP 函数,以根据 WordPress 帖子和页面自动生成 XML。
add_action( 'send_headers', 'custom_send_headers');
if( !function_exists('custom_send_headers') ) :
function custom_send_headers( )
{
global $route, $wp_query, $window_title;
$bits = explode( "/", $_SERVER['REQUEST_URI'] );
if( $bits[1] === 'sitemap.xml' )
{
if ( $wp_query->is_404 ) {
$wp_query->is_404 = false;
}
include('sitemap.php');
die();
}
}
endif;
一切正常,我的 PHP 文件包含适当的 headers:
<?php header('Content-Type: application/xml'); ?>
<?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
....
</urlset>
为什么 WordPress 会发送 404?
我尝试使用 WordPress 模板,但似乎不起作用。
$template = locate_template('sitemap.php');
load_template($template);
还有其他我应该挂钩的功能吗?我是否错过了我应该做的其他事情?
您可能仍需要发送 200 OK
header,因为您正在绕过发送内容的正常方法。
在 include('sitemap.php');
header("HTTP/1.1 200 OK");