在寻找一个非常具体的用例时,我稍微修改了@Loctor antonio cezar的代码。我需要一个专门为谷歌新闻写的网站地图。有什么不同?整个标记如下the rules. 就我的具体情况而言,我将帖子数量限制在20个。超过2天的帖子也会消失。也许有人需要这个:
/* 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() {
if ( str_replace( \'-\', \'\', get_option( \'gmt_offset\' ) ) < 10 ) {
$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\' => 20,
\'orderby\' => \'modified\',
\'post_type\' => array( \'post\', \'page\' ),
\'order\' => \'DESC\',
\'date_query\' => array(
\'after\' => date(\'Y-m-d\', strtotime(\'-2 days\'))
)
) );
$sitemap .= \'<?xml version="1.0" encoding="UTF-8"?>\';
$sitemap .= "\\n" . \'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">\' . "\\n";
foreach( $postsForSitemap as $post ) {
setup_postdata( $post);
$postdate = explode( " ", $post->post_modified );
$sitemap .= "\\t" . "<url>" . "\\n";
$sitemap .= "\\t\\t" . "<loc>" . get_permalink( $post->ID ) . \'</loc>\';
$sitemap .= "\\t\\t" . \'<news:news>\' . "\\n";
$sitemap .= "\\t\\t\\t" . \'<news:publication>\' . "\\n";
$sitemap .= "\\t\\t\\t\\t" . \'<news:name><![CDATA[ YOUR SITE ]]></news:name>\' . "\\n";
$sitemap .= "\\t\\t\\t\\t" . \'<news:language>YOUR LANGUAGE</news:language>\' . "\\n";
$sitemap .= "\\t\\t\\t" . \'</news:publication>\' . "\\n";
$sitemap .= "\\t\\t\\t<news:publication_date>" . $postdate[0] . \'T\' . $postdate[1] . $tempo . "</news:publication_date>\\n";
$sitemap .= "\\t\\t\\t" . \'<news:title><![CDATA[\' . get_the_title( $post) . \']]></news:title>\' . "\\n";
$sitemap .= "\\t\\t" . \'</news:news>\' . "\\n";
$sitemap .= "\\t" . \'</url>\' . "\\n";
}
$sitemap .= \'</urlset>\';
$fp = fopen( ABSPATH . "sitemap_news.xml", \'w\' );
fwrite( $fp, $sitemap );
fclose( $fp );
}