Lightweight custom wordpress sitemap (pages, blog)

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 '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
        
        // Manually inject the Homepage with top priority
        echo '<url>' . "\n";
        echo '<loc>' . esc_url(home_url('/')) . '</loc>' . "\n";
        echo '<changefreq>daily</changefreq>' . "\n";
        echo '<priority>1.0</priority>' . "\n";
        echo '</url>' . "\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 '<url>' . "\n";
                echo '<loc>' . get_permalink() . '</loc>' . "\n";
                echo '<lastmod>' . get_the_modified_time('Y-m-d\TH:i:s+00:00') . '</lastmod>' . "\n";
                echo '<changefreq>weekly</changefreq>' . "\n";
                // Pages get slightly higher priority than blog posts
                echo '<priority>' . (is_page() ? '0.8' : '0.6') . '</priority>' . "\n"; 
                echo '</url>' . "\n";
            }
            wp_reset_postdata();
        }
        
        echo '</urlset>';
        exit; // Stop WordPress from loading the rest of the site template
    }
}
				
			

More Articles