wordpress无插件实现sitemap生成器

seo是每个站长都应该关注的话题,而在seo中sitemap.xml文件对于网站尤其是一个小型的网站比如博客来说是相当相当的重要,该文件能够帮助搜索引擎蜘蛛更好的爬取网站的内容,更好的了解一个站,而方便了蜘蛛,我们就可能获得加速收录的特权。

在wordpress中生成sitemap的插件很多,但是如果现在你去一一安装就会发现要么收费,要么不好用,我一直一直在用Baidu Sitemap Generator这个插件,但是最近点进去发现这个插件不工作了,卸载后本来准备重装试试,结果发现这个插件不知道什么时候下线了wordpress插件库,再下载安装了一众插件之后没有找到自己想要的后,决定还是自己新造一个轮子,但问题是怎么做呢?

既然要造一个新轮子,我们首先要明确我们要实现什么功能或解决什么问题?这里我希望在发布或者更新文章之后动态的生成或更新sitemap.xml文件,而不是像大部分生成器插件做的一样需要在发布或更新文章之后手动点击某一个生成按钮才能更新sitemap,或者是设置什么劳什子定时任务去定时更新sitemap,完全没必要。

wordpress提供了丰富的钩子函数来帮助开发者扩展他们的wordpress应用,现在明确了我们需要在文章发布或者更新之后动态的更新sitemap,那么很容易就可以找到publish_post这个钩子函数,该钩子函数接受一个参数$post_ID,在发布或更新文章时都会触发,所以我们只需要在执行这个钩子时执行更新sitemap的逻辑就好了,接下来的重点就是实现更新sitemap。

首先我们在主题目录下新建inc目录(和functions.php同级目录), 并新建文件sitemap.php用于编写生成sitemap的逻辑,因为这个说白了就是遍历,所以直接给出代码:

<?php
  $posts_limit = 1000;
  ob_start();
  echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="http://www.baidu.com/schemas/sitemap-mobile/1/">
<url>
  <loc><?php echo get_option("home"); ?></loc>
  <priority>1</priority>
</url>
<?php
  // 显示文章
  $args = array(
    'showposts' => $posts_limit
  );
  query_posts($args);
  while ( have_posts() ) : the_post();
?>
<url>
    <loc><?php the_permalink(); ?></loc>
    <lastmod><?php the_time('c') ?></lastmod>
    <priority>0.8</priority>
</url>
<?php endwhile;wp_reset_query(); ?>
<?php
  // 显示页面
  $mypages = get_pages();
    if (count($mypages) > 0) :
      foreach ($mypages 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>
    <priority>0.6</priority>
</url>
<?php endforeach;endif; ?>
<?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>
    <priority>0.6</priority>
</url>
<?php endforeach;endif; ?>
<?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>
   <priority>0.4</priority>
</url>
<?php endforeach; ?>
</urlset>
<?php
  $content = ob_get_contents();
  ob_end_clean();
  file_put_contents('./sitemap.xml', $content);
?>

我们也可以在此基础上做一些发挥比如将一些选项弄成后台配置化,比如显示数量,比如是否列出文章,是否列出页面,是否列出分类,是否列出标签,并将这些配置功能集成到自己的主题中,或者做成一个插件,这个就看自己发挥了。

我们现在已经有了生成sitemap的逻辑,接下来就是将其集成到项目中,是文章更新后能够执行更新,我们只需要在主题目录下的functios.php加入代码:

function generateSitemap() {
     require_once(get_template_directory() . '/inc/sitemap.php');
  }
add_action('publish_post','generateSitemap');

这样以后每次发布或者更新文章都能及时的生成最新的sitemap了。

文末提供本文示例源码包,如有需要请自行下载。

猛戳这里下载本文案例源码包

  • 支付宝二维码 支付宝
  • 微信二维码 微信
相关文章