How to create sitemap.xml for page without plugin in wordpress

Posted: April 14, 2022 in Uncategorized
Tags: ,
  1. Fetch all pages by using wp_query (dont forgot to all wp_reset_query at the end)
  2. Bind all data with sitemap tags
  3. add sitemap.xml file to wordpress root directory
$postsForSitemap=<YOUR WP QUERY RESULT>
//generate sitemap
	$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 );

		$permalink = get_permalink($post->ID);	

		$sitemap .= '<url>'.
		'<loc>' .  $permalink. '</loc>' .
		'<lastmod>' .date('Y-m-d', $post->_lastMod) . '</lastmod>' .
		'<changefreq>' .  $post->_changeFreq. '</changefreq>'.
		'<priority>' . $post->_priority. '</priority>'.
		'</url>';
	}

	$sitemap .= '</urlset>';

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

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

Leave a comment