Don’t forget to flush permalinks after inserting the code.
/* ==========================================================================
DCODEHUB DYNAMIC XML SITEMAP GENERATOR
========================================================================== */
// 1. Tell WordPress to listen for the sitemap.xml URL
add_action('init', 'dcodehub_sitemap_rewrite_rule');
function dcodehub_sitemap_rewrite_rule() {
add_rewrite_rule('^sitemap\.xml$', 'index.php?dcodehub_sitemap=1', 'top');
}
// 2. Register the custom query variable
add_filter('query_vars', 'dcodehub_sitemap_query_vars');
function dcodehub_sitemap_query_vars($vars) {
$vars[] = 'dcodehub_sitemap';
return $vars;
}
// 3. Build and output the actual XML structure
add_action('template_redirect', 'dcodehub_sitemap_template');
function dcodehub_sitemap_template() {
if (get_query_var('dcodehub_sitemap')) {
// Send the correct headers to the browser and Google
header('Content-Type: text/xml; charset=utf-8');
echo '' . "\n";
echo '' . "\n";
// Manually inject the Homepage with top priority
echo '' . "\n";
echo '' . esc_url(home_url('/')) . ' ' . "\n";
echo 'daily ' . "\n";
echo '1.0 ' . "\n";
echo ' ' . "\n";
// Fetch all published Pages and Posts
$args = array(
'post_type' => array('page', 'post'),
'post_status' => 'publish',
'posts_per_page' => -1,
'has_password' => false, // Don't include password-protected pages
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
// Skip the homepage so it doesn't show up twice
if (get_the_ID() == get_option('page_on_front')) continue;
echo '' . "\n";
echo '' . get_permalink() . ' ' . "\n";
echo '' . get_the_modified_time('Y-m-d\TH:i:s+00:00') . ' ' . "\n";
echo 'weekly ' . "\n";
// Pages get slightly higher priority than blog posts
echo '' . (is_page() ? '0.8' : '0.6') . ' ' . "\n";
echo ' ' . "\n";
}
wp_reset_postdata();
}
echo ' ';
exit; // Stop WordPress from loading the rest of the site template
}
}