WordPress纯代码实现自动生成网站地图

百度不支持索引模式的sitemap,而wordpress默认不带sitemap.xml,即使多站点模式自动生成的sitemap也偏偏是索引模式,为了弥补这一缺陷,本文分享一段可以自动生成站点地图的代码。

0x01 代码

在Wordpres网站根目录创建文件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="https://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="https://www.baidu.com/schemas/sitemap-mobile/1/">'
?>
  <url>
    <loc><?php echo get_home_url(); ?></loc>
    <mobile:mobile type="pc,mobile"/>
    <lastmod><?php $ltime = get_lastpostmodified(GMT);$ltime = gmdate('Y-m-dTH: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>
    <mobile:mobile type="pc,mobile"/>
    <lastmod><?php the_time('c') ?></lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.6</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>
      <mobile:mobile type="pc,mobile"/>
      <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>
      <mobile:mobile type="pc,mobile"/>
      <changefreq>weekly</changefreq>
      <priority>0.8</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>
    <mobile:mobile type="pc,mobile"/>
    <changefreq>monthly</changefreq>
    <priority>0.4</priority>
  </url>
<?php } ?>
</urlset>

备注:这段代码在网上一搜一大把,也不知谁是原创,故本人也不注明来源了。

0x02 伪静态

修改nginx/apache的伪静态规则,以Nginx为例,在server区域的“location /”代码段添加代码:

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

0x03 百度搜索

登录百度搜索资源平台,在“资源提交→普通收录→sitemap”中添加站点sitemap.xml链接。

原创文章禁止转载:技术学堂 » WordPress纯代码实现自动生成网站地图

精彩评论

1+8=

感谢您的支持与鼓励

支付宝扫一扫打赏

微信扫一扫打赏