SEO WordPress

对于页面的description和keywords的设置WordPress 默认的情况是把在撰写日志的时候添加摘要(excerpt)作为description而把添加的标签(tag)作为keywords,但是大部分的人通常只添加keywords而很少会在发表日志的时候添加摘要(excerpt)这样一来很多页面就不会有description,下面的代码的作用就是如果写日志的时候给日志添加了摘要的就把摘要做为页面的Description,如果没有设置摘要的话,则自动截取文章的前120个字作为Description,而标签直接作为Keywords。
代码如下:

post_excerpt) {
         $description     = $post->post_excerpt;
     } else {
         $description = substr(strip_tags($post->post_content),0,120);
     }       $keywords = "";
            $tags = wp_get_post_tags($post->ID);
     foreach ($tags as $tag ) {
         $keywords = $keywords . $tag->name . ", ";
     } } ?>

上面代码请放到header.php中下面两行代码的上面

<meta name="keywords" content="<?=$keywords?>"  />
<meta name="description" content="<?=$description?>"  />

修改好文件之后查看源代码可能会发现一个问题就是如果内容是中文的有时候会发现description乱码
后来查了相关资料后发现是上面代码中的

$description = substr(strip_tags($post->post_content),0,120);

这行代码中的substr函数导致的把这行代码改成这样就可以了

$description = mb_substr(strip_tags($post->post_content),0,120,'utf-8');

改完之后如果发现打开页面出现错误,请看blog中的这篇文章
http://www.78wd.com/mb-substr/

About pangel

i am shadow
This entry was posted in Code and tagged , . Bookmark the permalink. [69 views]

Related Posts

Comments are closed.