Software Developer

Automatically Add Scheduled Posts URL to sitemap.xml in WordPress

This function will automatically add the post URL to your XML sitemap file when it is published, if it was a scheduled post in WordPress. In other words, for all scheduled posts in WordPress, once they become published, their URL will be added to your XML sitemap.

This assumes two things:

  1. Your sitemap.xml lives at the root of your site.
  2. You want to set the priority of these URLs as 0.7 on the sitemap.xml.

If not, you can alter those two values in the code. You can alter the path your sitemap file on line 6. You can alter the 0.7 priority on line 8.

/**
 * Add URL to sitemap.xml when scheduled post is published
 *
 */
function add_url_to_sitemap( $post ) {
 	$f = $_SERVER['DOCUMENT_ROOT'] . '/sitemap.xml';
 	$fo = fopen($f, 'r+');
 	$i = '<url><loc>' . get_permalink($post) . '</loc><lastmod>'. date('c') .'</lastmod><changefreq>yearly</changefreq><priority>0.7</priority></url></urlset>';
 	fseek( $fo, -9, SEEK_END );
 	fwrite( $fo, $i );
 	fclose( $fo );
}
add_action('future_to_publish', 'add_url_to_sitemap', 10, 1);

By

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]