How to create sitemap.xml without plugin for WordPress

Sitemap

It is very important to have a sitemap to index the uploaded content of the website in the proper search engine.

If you are a user of WordPress and you want to create a sitemap.xml file on your website and upload it in your WordPress then you can do so. For that you follow the step given below –

1 – function.php
You patse the following code in function.php

function xml_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);

$sitemap .= '<url>'.
'<loc>'. get_permalink($post->ID) .'</loc>'.
'</url>';
}

$sitemap .= '</urlset>';

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

add_action("publish_post", "xml_sitemap");
add_action("publish_page", "xml_sitemap");
?>

with last modified date

function xml_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 = date( DATE_W3C, strtotime( $post->post_modified_gmt ) );
$sitemap .= '<url>'.
'<loc>'. get_permalink($post->ID) .'</loc>'.
'<lastmod>'. $postdate .'</lastmod>'.
'</url>';
}

$sitemap .= '</urlset>';

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

add_action("publish_post", "xml_sitemap");
add_action("publish_page", "xml_sitemap");
?>

In this way you can create sitemap.xml in your website without plugins. If you want to make automatically sitemaps when execute url limits or per sitemap, So click-here  and follow instructions.