Skip to content

Instantly share code, notes, and snippets.

@alfonso100
Created January 24, 2025 14:06
Show Gist options
  • Save alfonso100/42bd138d4290347821a018b9a690c100 to your computer and use it in GitHub Desktop.
Save alfonso100/42bd138d4290347821a018b9a690c100 to your computer and use it in GitHub Desktop.
wpr-sitemap-generator.php
// Create a custom sitemap with the lastest n posts, and updates it after saving a post.
// Useful for big sites.
// Writes an xml file in the root level of the wp install: https://example/my-custom-sitemap.xml
add_action( "save_post", "wpr_create_custom_sitemap" );
function wpr_create_custom_sitemap() {
if ( str_replace( '-', '', get_option( 'gmt_offset' ) ) < 0 ) {
$tempo = '-0' . str_replace( '-', '', get_option( 'gmt_offset' ) );
} else {
$tempo = get_option( 'gmt_offset' );
}
if( strlen( $tempo ) == 3 ) { $tempo = $tempo . ':00'; }
$postsForSitemap = get_posts( array(
'numberposts' => 2, // this is the number of pages, change it accordingly
'orderby' => 'modified',
'post_type' => array( 'post', 'page' ),
'order' => 'DESC'
) );
$sitemap .= '<?xml version="1.0" encoding="UTF-8"?>' . '<?xml-stylesheet type="text/xsl" href="' .
esc_url( home_url( '/' ) ) . 'sitemap.xsl"?>';
$sitemap .= "\n" . '<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
$sitemap .= "\t" . '<url>' . "\n" .
"\t\t" . '<loc>' . esc_url( home_url( '/' ) ) . '</loc>' .
"\n\t\t" . '<lastmod>' . date( "Y-m-d\TH:i:s", current_time( 'timestamp', 0 ) ) . $tempo . '</lastmod>' .
"\n\t\t" . '<changefreq>daily</changefreq>' .
"\n\t\t" . '<priority>1.0</priority>' .
"\n\t" . '</url>' . "\n";
foreach( $postsForSitemap 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] . 'T' . $postdate[1] . $tempo . '</lastmod>' .
"\n\t\t" . '<changefreq>Weekly</changefreq>' .
"\n\t\t" . '<priority>0.5</priority>' .
"\n\t" . '</url>' . "\n";
}
$sitemap .= '</urlset>';
$fp = fopen( ABSPATH . "my-custom-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