WordPress 自动生成sitemap.xml
现在收录普遍慢,所以sitemap.xml显得尤为重要,其实wordpress是自带sitemap的功能,但是wordpress自带的sitemap对百度并不友好。可以在wp站点的网站后面添加wp-sitemap.xml来查看wordpress自带的sitemap功能。
所以我写了一个新的sitemap功能,当任意文章更新或者删除的时候,会在站点根目录生成一个静态的sitemap.xml,直接把代码复制到主题下面的functions.php就可以了。
add_action("publish_post", "yxseo_create_sitemap");
add_action("publish_page", "yxseo_create_sitemap");
function yxseo_create_sitemap() {
$postsForSitemap = get_posts(array(
'numberposts' => -1,
'orderby' => 'modified',
'post_type' => array('post','page'),
'order' => 'DESC'
));
$sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
$sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
//首页
$post = $postsForSitemap[0];
setup_postdata( $post );
$postdate = explode(" ", $post->post_modified);
$sitemap .= '<url>'.
'<loc>'. get_bloginfo('url') .'/</loc>'.
'<priority>1</priority>'.
'<lastmod>'. $postdate[0] .'</lastmod>'.
'<changefreq>daily</changefreq>'.
'</url>';
//分类页面
$catlist = get_categories();
foreach($catlist as $subcat){
$sitemap .= '<url>'.
'<loc>'. get_category_link( $subcat->term_id ) .'/</loc>'.
'<priority>1</priority>'.
'<lastmod>'. $postdate[0] .'</lastmod>'.
'<changefreq>daily</changefreq>'.
'</url>';
}
//内容页面
foreach($postsForSitemap as $post) {
setup_postdata($post);
$postdate = explode(" ", $post->post_modified);
$sitemap .= '<url>'.
'<loc>'. get_permalink($post->ID) .'</loc>'.
'<priority>1</priority>'.
'<lastmod>'. $postdate[0] .'</lastmod>'.
'<changefreq>daily</changefreq>'.
'</url>';
}
$sitemap .= '</urlset>';
$fp = fopen(ABSPATH . "sitemap.xml", 'w');
fwrite($fp, $sitemap);
fclose($fp);
}
发表回复