frederik's blog

Music (5) Projects (2) Snippets (8) Technology (5) Thoughts (9)


Create WordPress sitemaps on the fly without plugins

/ (last edited)

I found this snippet for creating sitemaps on an old thumbdrive and it works fine with the latest WordPress (4.9.4) – no need for yet another bloated, ad-riddled WordPress plugin!

It’s simple and it gets the job done. No options to tune, nothing to worry about later. I put the code in my theme’s functions.php and every time a post is published (or updated), the sitemap is regenerated as a proper sitemap.xml file in the blog’s root folder. It can be used with the Google Search Console for example.

Here is the output from my own blog:

/* call our function when saving or publishing posts/pages */
add_action('publish_post', 'noplug_sitemap');
add_action('publish_page', 'noplug_sitemap');
add_action('save_post', 'noplug_sitemap');
add_action('save_page', 'noplug_sitemap');

function noplug_sitemap() {

    /* retrieve all published posts and pages */
    $all_the_posts = get_posts(array(
        'numberposts' => -1,
        'orderby' => 'modified',
        'post_type'  => array('post', 'page'),
        'order'    => 'DESC'

    /* Prepare the XML file */
    $sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
    $sitemap .= '<urlset xmlns="">';

    /* Loop through all retrieved posts */    
    foreach($all_the_posts as $post) {

        $postdate = explode(" ", $post->post_modified);

        /* This is where the entries are built */		
        $sitemap .= '<url><loc>' . get_permalink($post->ID) . '</loc><lastmod>' . $postdate[0] . '</lastmod>' .
          '<changefreq>monthly</changefreq>' .

    $sitemap .= '</urlset>';

    /* You can rename the file of course if you prefer */
    $fp = fopen(ABSPATH . 'sitemap.xml', 'w');
    fwrite($fp, $sitemap);

There are many similiar snippets on the web. This one could be turned into a plugin easily. But why bother if it fits into the functions.php so nicely. Functional WordPress sitemaps without plugins are indeed possible – I’m not really surprised since most of the functionality I need for running my blogs is implemented without plugins.