frederik's blog

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

Speak×

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: frjk.de/blog/sitemap.xml

/* 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="http://www.sitemaps.org/schemas/sitemap/0.9">';

    /* Loop through all retrieved posts */    
    foreach($all_the_posts as $post) {
        setup_postdata($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>' .
         '</url>';
      }

    $sitemap .= '</urlset>';

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *