订阅本站

对于WordPress 的 Description 与 Keywords 实现有很多方法,最简单的是用All in One SEO Pack 插件,但是插件多了影响效率,那我们就直接在模板(header.php)里面用代码实现这个功能。

SEO代码经过几代更新,终于又了一个接近完美的版本。如果有摘要就使用摘要作为描述,如果没有就用下面注释的规则来截取描述,同时使用Tag来作为关键词。

  1. < ?php
  2. ##定义一个函数.解决截取中文乱码的问题
  3. if (!function_exists('utf8Substr')) {
  4.  function utf8Substr($str, $from, $len)
  5.  {
  6.      return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
  7.           '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
  8.           '$1',$str);
  9.  }
  10. }
  11.  if (is_home()){
  12. $description = "首页的描述";
  13. $keywords = "首页的关键词";
  14. } elseif (is_single()){
  15.     if ($post->post_excerpt) {
  16.         $description  = $post->post_excerpt;
  17.     } else {
  18. ###第一种情况,以<p>开始,</p>结束来取第一段
  19.    if(preg_match('/<p>(.*)<\/p>/iU',trim(strip_tags($post->post_content,"<p>")),$result)){
  20.     $post_content = $result['1'];
  21.    } else {
  22. ###第二种情况,以换行符(\n)来取第一段
  23. $post_content_r = explode("\n",trim(strip_tags($post->post_content)));
  24. $post_content = $post_content_r['0'];
  25.    }
  26.          $description = utf8Substr($post_content,0,220);   
  27.   }
  28.  
  29.     $keywords = "";     
  30.     $tags = wp_get_post_tags($post->ID);
  31.     foreach ($tags as $tag ) {
  32.         $keywords = $keywords . $tag->name . ",";
  33.     }
  34.  
  35. }
  36.  
  37. ?>
  38. <meta name="description" content="<?php echo trim($description); ?>" />
  39. <meta name="keywords" content="<?php echo rtrim($keywords,','); ?>" />

无觅相关文章插件,快速提升流量