对于WordPress 的 Description 与 Keywords 实现有很多方法,最简单的是用All in One SEO Pack 插件,但是插件多了影响效率,那我们就直接在模板(header.php)里面用代码实现这个功能。
SEO代码经过几代更新,终于又了一个接近完美的版本。如果有摘要就使用摘要作为描述,如果没有就用下面注释的规则来截取描述,同时使用Tag来作为关键词。
- < ?php
- ##定义一个函数.解决截取中文乱码的问题
- if (!function_exists('utf8Substr')) {
- function utf8Substr($str, $from, $len)
- {
- return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
- '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
- '$1',$str);
- }
- }
- if (is_home()){
- $description = "首页的描述";
- $keywords = "首页的关键词";
- } elseif (is_single()){
- if ($post->post_excerpt) {
- $description = $post->post_excerpt;
- } else {
- ###第一种情况,以<p>开始,</p>结束来取第一段
- if(preg_match('/<p>(.*)<\/p>/iU',trim(strip_tags($post->post_content,"<p>")),$result)){
- $post_content = $result['1'];
- } else {
- ###第二种情况,以换行符(\n)来取第一段
- $post_content_r = explode("\n",trim(strip_tags($post->post_content)));
- $post_content = $post_content_r['0'];
- }
- $description = utf8Substr($post_content,0,220);
- }
- $keywords = "";
- $tags = wp_get_post_tags($post->ID);
- foreach ($tags as $tag ) {
- $keywords = $keywords . $tag->name . ",";
- }
- }
- ?>
- <meta name="description" content="<?php echo trim($description); ?>" />
- <meta name="keywords" content="<?php echo rtrim($keywords,','); ?>" />