Create sitemap.xml In WordPress Without Using Any Plugins

Everybody likes plugins, and most of them are really great (in case of WordPress). But some people like me, tend to do the work by themselves.

So, here is a simple code that will re-create a sitemap.xml file, everytime you publish a post or page. Copy the code and paste it to your theme’s functions.php file (wp-content/themes/your_theme_folder/functions.php).

add_action("publish_post", "eg_create_sitemap");
add_action("publish_page", "eg_create_sitemap");

function eg_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="">';

  foreach($postsForSitemap as $post) {

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

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

  $sitemap .= '</urlset>';

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

If you’ve got custom post types, you’ll need to add the registered taxonomy to ‘post_type’ array part of the code.

For a big blog with thousands of posts, creating a sitemap.xml file with every post publish action might not be a good solution, so keep that in mind.