PHP部分
- 在网站根目录新建一个Sitemap.php文件
- 文件中填入以下代码:
<?php
// +----------------------------------------------------------------------
// | Author: 戏世之人 <6@7-89.cn>
// +----------------------------------------------------------------------
// | Date: 2019年9月1日
// +----------------------------------------------------------------------
// | Blog: www.xshi.cc 【戏世博客】
// +----------------------------------------------------------------------
// | Name: WordPress网站地图
// +----------------------------------------------------------------------
require('./wp-blog-header.php');
header("Content-type: text/xml");
header('HTTP/1.1 200 OK');
echo '<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 https://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
?>
<!-- generated-on=<?php echo get_lastpostdate('blog'); ?>-->
<url>
<loc><?php echo get_home_url(); ?></loc>
<lastmod><?php echo gmdate('Y-m-dTH:i:s+00:00', strtotime(get_lastpostmodified('GMT'))); ?></lastmod>
<changefreq>daily</changefreq>
<priority>1.0</priority>
</url>
<?php
// 文章
$posts = get_posts('numberposts=-1&orderby=post_date&order=DESC');
foreach($posts as $post) :
?>
<url>
<loc><?php echo get_permalink($post->ID); ?></loc>
<lastmod><?php echo str_replace(" ", "T", get_post($post->ID)->post_modified); ?>+00:00</lastmod>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<?php
endforeach;
// 页面
$pages = get_pages('numberposts=-1&orderby=post_date&order=DESC');
foreach($pages 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
endforeach;
// 分类
$categorys = get_terms('category', 'orderby=name&hide_empty=0');
foreach ($categorys as $category) :
?>
<url>
<loc><?php echo get_term_link($category, $category->slug); ?></loc>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<?php
endforeach;
// 标签
$tags = get_terms('post_tag', 'orderby=name&hide_empty=0');
foreach ($tags as $tag) :
?>
<url>
<loc><?php echo get_term_link($tag, $tag->slug); ?></loc>
<changefreq>monthly</changefreq>
<priority>0.4</priority>
</url>
<?php
endforeach;
?>
</urlset>
伪静态部分
Nginx在.htaccess添加以下重写规则:
//Code from https://www.xshi.cc/
rewrite ^/sitemap.xml$ /xmlmap.php;
Apache在.htaccess添加以下重写规则:
//Code from https://www.xshi.cc/
RewriteEngine On
RewriteBase /
RewriteRule ^Sitemap.xml$ Sitemap.php
其他
最后在网站底部添加Sitemap就可以供搜索引擎抓取了。