Code for Creating Sitemaps Automatically

Add given code on functions.php. If you don’t want to use any type of plugins for sitemap. So use this code and check your website’s sitemap after publish post.

//Disable Default WP sitemap

add_filter( 'wp_sitemaps_enabled', '__return_false' );

//Sitemap

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

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

$postdate = date(DATE_W3C, strtotime($post->post_modified_gmt));
$permalink = get_permalink($post->ID);
$sitemap .= '<url>'.
'<loc>' . $permalink . '</loc>'.
'<lastmod>' . $postdate . '</lastmod>'.
'</url>';
}

$sitemap .= '</urlset>';

return $sitemap;
}

function thekroyaard_sitemap_files() {
$postsForSitemap = get_posts(array(
'numberposts' => -1,
'orderby' => 'modified',
'post_type' => array('post', 'page'),
'order' => 'ASC' // Order by ASC
));

$urlsPerSitemap = 1000;
$totalPosts = count($postsForSitemap);
$totalChunks = ceil($totalPosts / $urlsPerSitemap);

$lastSitemapUrls = array(); // Store URLs of the most recent sitemap

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

for ($startIndex = 0; $startIndex < $totalPosts; $startIndex += $urlsPerSitemap) {
$chunk = array_slice($postsForSitemap, $startIndex, $urlsPerSitemap);
$sitemapContent = generate_sitemap($chunk);

$sitemapFileName = 'sitemap_' . ($startIndex / $urlsPerSitemap + 1) . '.xml';
$fp = fopen(ABSPATH . $sitemapFileName, 'w');
fwrite($fp, $sitemapContent);
fclose($fp);

$lastPostModified = end($chunk); // Get the last post in the chunk
$postdate = date(DATE_W3C, strtotime($lastPostModified->post_modified_gmt));

if ($startIndex === 0) {
$lastSitemapUrls = $chunk; // Store URLs of the most recent sitemap
}

$sitemapIndex .= '<sitemap>' .
'<loc>' . home_url() . '/' . $sitemapFileName . '</loc>' .
'<lastmod>' . $postdate . '</lastmod>' . // Use the last modified time of the last post in chunk
'</sitemap>';
}

$sitemapIndex .= '</sitemapindex>';

// Write the sitemap index XML
$fp = fopen(ABSPATH . "sitemap_index.xml", 'w');
fwrite($fp, $sitemapIndex);
fclose($fp);
}

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

This code used my me and this code works perfectly.