Skip to content

Instantly share code, notes, and snippets.

@wookiecooking
Created May 14, 2013 03:38
Show Gist options
  • Save wookiecooking/5573492 to your computer and use it in GitHub Desktop.
Save wookiecooking/5573492 to your computer and use it in GitHub Desktop.
[WordPress] Generates XML Sitemap
<?
/*
Plugin Name: Sitemap Generator
Description: Generates a XML sitemap For Google Webmaster tools
*/
// On publish of post, update sitemap
add_action("publish_post", "sitemap_gen");
// Update of page
add_action("publish_page", "sitemap_gen");
// If revised post/page
add_action("save_post", "sitemap_gen");
// On activation, create sitemap
register_activation_hook( __FILE__, 'sitemap_gen');
// Query DB for posts/pages, you can edit this to show custom posts type where noted
function sitemap_gen() {
$postsque = get_posts(array(
'numberposts' => -1,
'orderby' => 'modified',
'post_type' => array('post','page'), // array('post','page', 'Custom-Post-Type'),
'order' => 'DESC'
));
// Create XML
$sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
$sitemap .= "\n".'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n";
foreach($postsque as $post) {
setup_postdata($post);
$postdate = explode(" ", $post->post_modified);
$sitemap .= "\t".'<url>'."\n".
"\t\t".'<loc>'. get_permalink($post->ID) .'</loc>'.
"\n\t\t".'<lastmod>'. $postdate[0] .'</lastmod>'.
"\n\t\t".'<changefreq>monthly</changefreq>'.
"\n\t".'</url>'."\n";
}
$sitemap .= '</urlset>';
$fp = fopen(ABSPATH . "sitemap.xml", 'w');
fwrite($fp, $sitemap);
fclose($fp);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment