当前位置:蚂蚁分类目录 » 站长资讯 » 站长运营 » WordPress教程 » 文章详细 订阅RssFeed

如何实现WordPress 更新文章后自动更新站点 sitemap地图?

来源:互联网 浏览:1028次 时间:2021-05-09 22:20:37

当你的网站中不存在 sitemap.xml 文件时,只要你没有勾选“建议搜索引擎不索引该站点”时,当搜索引擎访问你的站点时,系统是会默认产生一个 sitemap 的(当然是伪静态的,对于这一点,是不需要插件的),但是这种方法可能不适合所有的搜索引擎,所以我们最好还是需要自己添加 sitemap.xml 文件,然后将它提交给搜索引擎。但是自己手动做 sitemap 很麻烦,需要经常改。于是,自动生成的方法应运而生,今天蚂蚁 分类就目录就来说说WordPress自动更新sitemap地图具体的实现方法。

在主题的 functions.php 文件中添加以下代码即可:

/* 当发布新文章时自动更新站点根目录的 sitemap.xml 文件 */
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' => -1,
'orderby' => 'modified',
'post_type' => array('post','page'),
'order'=> 'DESC'));
$sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
$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:mobile="http://www.baidu.com/schemas/sitemap-mobile/1/" 
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n";
$sitemap .= '<!-- generated-on=' . 
date( "Y-m-d\TH:i:s", current_time( 'timestamp', 0 ) ) . $tempo . '-->'."\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 . "sitemap.xml", 'w');
fwrite($fp, $sitemap);
fclose($fp);
}