WordPress 网站地图 sitemap.xml 纯代码设置方法【亲测有效】

可以同时生成首页、文章、单页面、分类和标签的 sitemap!

一、PHP 代码

code

  1. <?php
  2. require(‘./wp-blog-header.php’);
  3. header(“Content-type: text/xml”);
  4. header(‘HTTP/1.1 200 OK’);
  5. $posts_to_show = 1000;
  6. echo ‘<?xml version=”1.0″ encoding=”UTF-8″?>’;
  7. echo ‘<urlset xmlns=”http://www.sitemaps.org/schemas/sitemap/0.9″ xmlns:mobile=”http://www.baidu.com/schemas/sitemap-mobile/1/”>&#8217;
  8. ?>
  9.   <url>
  10.       <loc><?php echo get_home_url(); ?></loc>
  11.       <lastmod><?php $ltime = get_lastpostmodified(GMT);$ltime = gmdate(‘Y-m-dTH:i:s+00:00’, strtotime($ltime)); echo $ltime; ?></lastmod>
  12.       <changefreq>daily</changefreq>
  13.       <priority>1.0</priority>
  14.   </url>
  15. <?php
  16. /* 文章页面 */
  17. $myposts = get_posts( “numberposts=” . $posts_to_show );
  18. foreach( $myposts as $post ) { ?>
  19.   <url>
  20.       <loc><?php the_permalink(); ?></loc>
  21.       <lastmod><?php the_time(‘c’) ?></lastmod>
  22.       <changefreq>monthly</changefreq>
  23.       <priority>0.6</priority>
  24.   </url>
  25. <?php } /* 文章循环结束 */ ?>
  26. <?php
  27. /* 单页面 */
  28. $mypages = get_pages();
  29. if(count($mypages) > 0) {
  30.     foreach($mypages as $page) { ?>
  31.     <url>
  32.       <loc><?php echo get_page_link($page->ID); ?></loc>
  33.       <lastmod><?php echo str_replace(” “,”T”,get_page($page->ID)->post_modified); ?>+00:00</lastmod>
  34.       <changefreq>weekly</changefreq>
  35.       <priority>0.6</priority>
  36.   </url>
  37. <?php }} /* 单页面循环结束 */ ?>
  38. <?php
  39. /* 博客分类 */
  40. $terms = get_terms(‘category’, ‘orderby=name&hide_empty=0’ );
  41. $count = count($terms);
  42. if($count > 0){
  43. foreach ($terms as $term) { ?>
  44.     <url>
  45.       <loc><?php echo get_term_link($term, $term->slug); ?></loc>
  46.       <changefreq>weekly</changefreq>
  47.       <priority>0.8</priority>
  48.   </url>
  49. <?php }} /* 分类循环结束 */?>
  50. <?php
  51.  /* 标签(可选) */
  52. $tags = get_terms(“post_tag”);
  53. foreach ( $tags as $key => $tag ) {
  54.     $link = get_term_link( intval($tag->term_id), “post_tag” );
  55.          if ( is_wp_error( $link ) )
  56.           return false;
  57.           $tags[ $key ]->link = $link;
  58. ?>
  59.  <url>
  60.       <loc><?php echo $link ?></loc>
  61.       <changefreq>monthly</changefreq>
  62.       <priority>0.4</priority>
  63.   </url>
  64. <?php  } /* 标签循环结束 */ ?>
  65. </urlset>

将以上代码保存为 sitemap.php,传到网站根目录。

二、伪静态

Nginx
编辑已存在的 Nginx 伪静态规则,新增如下规则后(平滑)重启 nginx 即可:

code

  1. rewrite ^/sitemap.xml$ /sitemap.php last;

Apache
编辑网站根目录的 .htaccess ,加入如下规则:

code

  1. RewriteRule ^(sitemap).xml$ $1.php

做好伪静态规则后,就可以直接访问 sitemap.xml 看看效果了

温馨提示: 本文最后更新于2025-04-22 17:53:19,某些文章具有时效性,若有错误或已失效,请在下方 留言或联系 我的网站
© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容