<?php
/* Template Name: Google News Sitemap */

// 1. Force XML header and clear any theme styling
ob_clean();
header('Content-Type: application/xml; charset=utf-8');

echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">
    <?php
    $args = array(
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => 10,
        'date_query'     => array(
            array('after' => '48 hours ago'),
        ),
    );

    $news_query = new WP_Query($args);

    if ($news_query->have_posts()) :
        while ($news_query->have_posts()) : $news_query->the_post(); ?>
            <url>
                <loc><?php the_permalink(); ?></loc>
                <news:news>
                    <news:publication>
                        <news:name>NewsGhana24</news:name>
                        <news:language>en</news:language>
                    </news:publication>
                    <news:publication_date><?php echo get_the_date('c'); ?></news:publication_date>
                    <news:title><?php echo htmlspecialchars(get_the_title()); ?></news:title>
                </news:news>
            </url>
        <?php endwhile;
        wp_reset_postdata();
    endif; ?>
</urlset>
<?php exit; // This stops WordPress from loading your footer/header ?>