I’m trying to hook into the send_headers
function of WordPress so I can check to see if a sitemap.xml
was requested. That way, I can serve up a custom PHP function to automatically generate the XML based on WordPress posts and pages.
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;
Everything is serving up properly, and my PHP file is including the appropriate 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>
Why would WordPress be sending 404?
I tried using WordPress templates and that didn’t seem to work.
$template = locate_template('sitemap.php');
load_template($template);
Is there another function I should be hooking into? Did I miss something else that I should be doing?
You may still need to send a
200 OK
header since you’re circumventing the normal approach to sending content.Add
header("HTTP/1.1 200 OK");
before yourinclude('sitemap.php');