特点
✅ 纯代码,0 插件 ✅ 自动生成 sitemap.xml ✅ 自动包含 文章、页面、分类、标签 ✅ 完美支持 SEO ✅ 不会出现 XML declaration allowed only 错误 ✅ 轻量、无冗余、无数据库压力 ✅ 支持百度 / 谷歌搜索引擎
最终代码(直接复制到 functions.php 最底部)
<?php
// ==============================================
// WordPress 无插件生成 sitemap.xml
// 自动更新、纯净无错、搜索引擎友好
// ==============================================
add_action('init', 'custom_sitemap_xml');
function custom_sitemap_xml() {
if (strpos($_SERVER['REQUEST_URI'], 'sitemap.xml') === false) return;
ob_clean(); // 关键:清空多余输出,避免XML报错
header('Content-Type: text/xml; charset=utf-8');
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
// 1. 首页
echo '<url>';
echo '<loc>' . home_url() . '</loc>';
echo '<lastmod>' . get_lastpostmodified('GMT') . '</lastmod>';
echo '<changefreq>daily</changefreq>';
echo '<priority>1.0</priority>';
echo '</url>';
// 2. 固定页面(about、contact等)
$pages = get_posts([
'post_type' => 'page',
'post_status' => 'publish',
'numberposts' => -1,
]);
foreach ($pages as $p) {
echo '<url>';
echo '<loc>' . get_permalink($p->ID) . '</loc>';
echo '<lastmod>' . gmdate('Y-m-d\TH:i:s\Z', strtotime($p->post_modified_gmt)) . '</lastmod>';
echo '<changefreq>monthly</changefreq>';
echo '<priority>0.8</priority>';
echo '</url>';
}
// 3. 文章(post)
$posts = get_posts([
'post_type' => 'post',
'post_status' => 'publish',
'numberposts' => 100,
]);
foreach ($posts as $p) {
echo '<url>';
echo '<loc>' . get_permalink($p->ID) . '</loc>';
echo '<lastmod>' . gmdate('Y-m-d\TH:i:s\Z', strtotime($p->post_modified_gmt)) . '</lastmod>';
echo '<changefreq>weekly</changefreq>';
echo '<priority>0.9</priority>';
echo '</url>';
}
// 4. 分类
$categories = get_categories(['hide_empty' => 1]);
foreach ($categories as $c) {
echo '<url>';
echo '<loc>' . get_category_link($c->term_id) . '</loc>';
echo '<changefreq>weekly</changefreq>';
echo '<priority>0.6</priority>';
echo '</url>';
}
// 5. 标签
$tags = get_tags(['hide_empty' => 1]);
foreach ($tags as $t) {
echo '<url>';
echo '<loc>' . get_tag_link($t->term_id) . '</loc>';
echo '<changefreq>weekly</changefreq>';
echo '<priority>0.5</priority>';
echo '</url>';
}
echo '</urlset>';
exit;
}
