WordPress定时生成Sitemap XML(非插件)

本文介绍了一种使用WordPress定时任务生成sitemap.xml的方法,避免在文章发布时生成导致的卡顿问题。通过添加自定义代码,系统每天自动执行两次,将文章按每3000篇分割生成多个XML文件,并创建主索引文件sitemap.xml,提升网站性能。

文章作者:
阅读时间: 12 分钟
更新时间:2025年11月13日

只用WordPress定时任务去生成sitemap.xml,这样比网上很多方法是在保存、发布文章时生成xml好一些,不会造成处理文章卡的现象。在WordPress主题文件functions.php中或者使用Code Snippets插件添加自定义代码:

// 判断定时计划是否存在
if ( ! wp_next_scheduled( 'sitemap_xml' ) ) {
  wp_schedule_event( time(), 'twicedaily', 'sitemap_xml' ); // 每天两次
}
add_action( 'sitemap_xml', 'sitemap_xml_func' );
 
// 定时计划执行函数
function sitemap_xml_func() {
  // 获取文章数量
  $count_posts = wp_count_posts();
  if ( $count_posts ) {
    $published_posts = $count_posts->publish;
    $sitemap_num = $published_posts / 3000; // 每个xml文件最多包含3000篇文章
    $sitemap_num = ceil($sitemap_num);
 
    // 创建xml文件
    for ($i = 1; $i <= $sitemap_num; $i++) {
      $postsForSitemap = get_posts(array(
        'numberposts' => 3000,
        'orderby' => 'modified',
        'post_type'  => array('post'),
        'order'    => 'DESC',
        'offset' => 3000 * ($i - 1)
      ));
      $sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
      $sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
      foreach($postsForSitemap as $post) {
        setup_postdata($post);
        $post_url = get_permalink($post->ID);
        $post_date = get_the_modified_date( 'c',$post->ID );
 
        $sitemap .= '<url>'.
              '<loc>'. $post_url .'</loc>'.
            '<lastmod>'.  $post_date .'</lastmod>'.
              // '<lastmod>'. $postdate[0] .'</lastmod>'.
          // '<changefreq>monthly</changefreq>'.
          '</url>';
      }
      $sitemap .= '</urlset>';
      $fp = fopen(ABSPATH . "sitemap-".$i.".xml", 'w');
      fwrite($fp, $sitemap);
      fclose($fp);
    }
 
    // 创建sitemap.xml文件
    $sitemap_all = '<?xml version="1.0" encoding="UTF-8"?>';
    $sitemap_all .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    for ($i = 1; $i <= $sitemap_num; $i++) {
      $sitemap_all .= '<sitemap>'.
            '<loc>'. get_bloginfo('url') .'/sitemap-'.$i.'.xml</loc>'.
            '<lastmod>'. date('c') .'</lastmod>'.
          '</sitemap>';
    }
    $sitemap_all .= '</sitemapindex>';
    $fp = fopen(ABSPATH . "sitemap.xml", 'w');
    fwrite($fp, $sitemap_all);
    fclose($fp);
  }
}

这篇文章有用吗?

点击星号为它评分!

平均评分 0 / 5. 投票数: 0

到目前为止还没有投票!成为第一位评论此文章。

在AI工具中继续讨论:
曾凤祥
曾凤祥
WordPress技术负责人
WordPress 独立站开发领域 10+ 年实践经验,长期专注于外贸独立站搭建与 SEO 优化,累计服务企业客户数百家(含制造业、外贸企业、政府等行业)

相关文章

无论你是否已有网站,我们都能帮你把线上业务推上新高度
无论什么行业,都能快速拥有专业网站:
无论什么行业,都能快速拥有专业网站:

展示型官网 / 品牌站 / 外贸独立站,均有成熟模板与定制方案
无需懂代码:可视化编辑+我们指导,轻松启动 → 快速上线,抢占先机​
结构清晰、利于SEO与后期运营,降低长期维护成本

立即查看建站方案
网站加载慢、跳出高、询盘少?
网站加载慢、跳出高、询盘少?

老旧体验与技术隐患会直接拖累获客与转化。
我们提供:网站全面诊断 → 速度/安全/结构优化 → 可持续运维支持(技术+策略),让网站真正成为您的业务增长工具,而不只是“线上门面”。

马上获取专属优化方案
微信联系
chat 扫码联系
模板建站
挑选模板
网站定制
免费诊断
咨询热线
咨询热线

189-0733-7671

返回顶部