WordPress – How to automatically create sitemap.xml without plugin

The following code will automatically create a sitemap.xml when a post or page is first published.

This is a non-plugin way to automatically create the sitemap.xml file – less bloat, straight to the point.

Instructions

  1. Save the code below to your preferred location (if you haven’t already I highly recommend you create a WordPress plugin for your custom functions)
  2. Hit update on an existing page or post to generate a new sitemap.xml file
  3. Check the new sitemap.xml file is accessible via the web – e.g. https://www.itsupportguides/sitemap.xml
  4. Optional: Submit the sitemap to Google for indexing

 

If you’re not sure where to place this code I highly recommend you read How to create a WordPress plugin for your custom functions.

add_action( 'publish_post', 'itsg_create_sitemap' );
add_action( 'publish_page', 'itsg_create_sitemap' );

function itsg_create_sitemap() {

    $postsForSitemap = get_posts(array(
        'numberposts' => -1,
        'orderby' => 'modified',
        'post_type'  => array( 'post', 'page' ),
        'order'    => 'DESC'
    ));

    $sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
    $sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

    foreach( $postsForSitemap as $post ) {
        setup_postdata( $post );

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

        $sitemap .= '<url>'.
          '<loc>' . get_permalink( $post->ID ) . '</loc>' .
          '<lastmod>' . $postdate[0] . '</lastmod>' .
          '<changefreq>monthly</changefreq>' .
         '</url>';
      }

    $sitemap .= '</urlset>';

    $fp = fopen( ABSPATH . 'sitemap.xml', 'w' );

    fwrite( $fp, $sitemap );
    fclose( $fp );
}