正文
站点地图可以方便网站管理员告诉搜索引擎它的网站上有哪些可供抓取的网页链接,最简单的站点地图形式,就是sitemap.xml文件,在其中列出网站中的网址以及关于每个网址的其他元数据(上次更新的时间、更改的频率以及相对于网站上其他网址的重要程度),以便搜索引擎可以更加智能地抓取网站
对于wordpress生成sitemap.xml地图,国内已经有人写了专门的插件,比较知名的有柳城的Baidu Sitemap Generator,国外的也有Google XML Sitemaps,我感觉就只是为了生成个sitemap.xml都用插件有点浪费资源,所以就用代码实现吧,代码是百度抄来的,我自己改了一下,已经支持生成标签和分类的xml了,还增加了sitemap.xml生成时间
php代码
新建一个sitemap.php
文件,将以下代码写入该文件
<?php
require('./wp-blog-header.php');
header("Content-type: text/xml");
header('HTTP/1.1 200 OK');
$posts_to_show = 1000;
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="http://www.baidu.com/schemas/sitemap-mobile/1/">'
?>
<!-- 生成时间 <?php echo $showtime=date("Y-m-d H:i:s");?> -->
<url>
<loc><?php echo get_home_url(); ?></loc>
<lastmod><?php $ltime = get_lastpostmodified(GMT);$ltime = gmdate('Y-m-d\TH:i:s+00:00', strtotime($ltime)); echo $ltime; ?></lastmod>
<changefreq>daily</changefreq>
<priority>1.0</priority>
</url>
<?php
//文章
$myposts = get_posts( "numberposts=" . $posts_to_show );
foreach( $myposts as $post ) { ?>
<url>
<loc><?php the_permalink(); ?></loc>
<lastmod><?php the_time('c') ?></lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<?php } ?>
<?php
//页面
$mypages = get_pages();
if(count($mypages) > 0) {
foreach($mypages as $page) { ?>
<url>
<loc><?php echo get_page_link($page->ID); ?></loc>
<lastmod><?php echo str_replace(" ","T",get_page($page->ID)->post_modified); ?>+00:00</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<?php }} ?>
<?php
//分类
$terms = get_terms('category', 'orderby=name&hide_empty=0' );
$count = count($terms);
if($count > 0){
foreach ($terms as $term) { ?>
<url>
<loc><?php echo get_term_link($term, $term->slug); ?></loc>
<changefreq>weekly</changefreq>
<priority>0.4</priority>
</url>
<?php }} ?>
<?php
//标签
$tags = get_terms("post_tag");
foreach ( $tags as $key => $tag ) {
$link = get_term_link( intval($tag->term_id), "post_tag" );
if ( is_wp_error( $link ) )
return false;
$tags[ $key ]->link = $link;
?>
<url>
<loc><?php echo $link ?></loc>
<changefreq>weekly</changefreq>
<priority>0.2</priority>
</url>
<?php } ?>
</urlset>
将sitemap.php
上传到网站根目录,然后访问查看效果...
伪静态方案
Nginx:编辑已存在的nginx伪静态规则,新增如下规则后重启nginx即可
rewrite ^/sitemap.xml$ /sitemap.php last;
Apache:编辑网站根目录的.htaccess,加入如下规则
RewriteRule ^(sitemap)\.xml$ $1.php
纯静态方案
Linux定时任务+wget定时生成sitemap.xml(该方案适合vps用户,不适用于虚拟主机)
将网站根目录的sitemap.php
重命名为一个只有自己知道的php文件,比如xml.php
然后用linux定时任务执行以下命令,然后将数据保存为sitemap.xml存放到网站根目录就可以了
wget -O /home/www/www.ikxin.com/sitemap.xml https://www.ikxin.com/sitemap.php
https://www.ikxin.com/sitemap.php
是php的路径
/home/www/www.ikxin.com/sitemap.xml
是xml文件存放路径
这样一来,就解决了sitemap.xml是动态数据问题了...