How to Create You WordPress XML Sitemap?


Hi go your wordpress theme functions.php, Then put your below code for xml site map purpose :

/* function to create sitemap.xml file in root directory of site  */

//add_action(“publish_post”, “eg_create_sitemap”);
//add_action(“publish_page”, “eg_create_sitemap”);

add_action(“save_post”, “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 .= “n”.'<urlset xmlns=”http://www.sitemaps.org/schemas/sitemap/0.9″>’.”n”;

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

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

$sitemap .= “t”.'<url>’.”n”.
“tt”.'<loc>’. get_permalink($post->ID) .'</loc>’.
“ntt”.'<lastmod>’. $postdate[0] .'</lastmod>’.
“ntt”.'<changefreq>monthly</changefreq>’.
“nt”.'</url>’.”n”;
}

$sitemap .= ‘</urlset>’;

$fp = fopen(ABSPATH . “sitemap.xml”, ‘w’);
fwrite($fp, $sitemap);
fclose($fp);
}

This is working when update your wordpress page or post. I create my side one empty sitemap.xml file in my theme. Then its working fine.

once you done this. You go to your page where you want link, you give that.
Ex: <a href=”/sitemap.xml” target=”_blank”>Sitemap</a>

Now this working, 🙂 Enjoy.

Comments are closed.