网站的sitemap.xml文件对网站的收录有着很重要的作用,但凡需要手动提交到搜索引擎的都需要提交这个网站地图文件,但wordpress默认的sitemap.xml有点low,在这期间也搜索了几款sitemap.xml生成的插件,WordPress官方插件库的免费插件也有功能不错的,但有点不合自己心意,付费搜索引擎优化的插件也有不错的,比如Yoast等,都需要付费,于是就琢磨使用PHP自己生成sitemap.xml文件,现将代码和使用方法和大家分享!
使用方法:
把以下代码复制粘贴到你WordPress主题的function.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);
}
声明:本站所有文章,除做原创说明之外均为网上搜集,不保证安全性和完整性,用于学习研究目的,请勿将其用于商业或非法用途。
您必须在下载后的24小时内彻底从你的磁盘中删除。如果您喜欢这些内容,请支持正版软件,购买注册授权,得到更好的正版服务。
更多声明内容请参考免责声明
您必须在下载后的24小时内彻底从你的磁盘中删除。如果您喜欢这些内容,请支持正版软件,购买注册授权,得到更好的正版服务。
更多声明内容请参考免责声明