Tags: Posted in SEO技术,wordpress 7 条留言

All in One SEO的确是个不错的插件,但是对于我这种不喜欢装太多插件的完美主义者,通过代码来实现Wordpress的Title,Meta优化是更好的选择。

网上关于Wordpress的Title,Meta优化方面的内容也很多了,但代码都不完整,存在各种各样的问题。

我遇到的问题:

1.title里文字前面出现空格

2.keywords标签里最后一个关键词后面还有一个逗号

3.部分页面的keywords,description内容为空,有的页面description里有换行

在网上搜索了很久,最后得到了完美解决方法,完全可以替代All in One SEO

WordPress Title优化

<title><?php if (is_home() ) { ?>博客标题<?php } else {?><?php wp_title(”); ?> – 博客标题<?php } ?></title>

这段代码实现的功能就是首页title显示博客标题,其它页面title为“页面名字 – 博客标题”。如果你喜欢“|博客标题”这种形式,可自行修改。

但是使用这种方法有点缺点,就是我说的1问题,title前面出现空格。解决办法:

wordpress后台->外观->编辑->找到functions.php->添加代码

// Removes the spaces from wp_title
function af_titledespacer($title) {
return trim($title);
}
add_filter(‘wp_title’, ‘af_titledespacer’);

$keywords = substr($keywords,0,-2);

WordPress Meta优化
有两种方法

第一种:获取文章的tags作为文章的keywords,把文章摘要(如果没有摘要则截取文章前220字)作为文章的description

第二种:通过Wordpress的自定义域功能实现

解决keywords最后一个关键词后出现逗号的方法:

在tag循环外加代码:$keywords = substr($keywords,0,-2);

description里有换行的解决方法:

$description = str_replace(array(“\r\n”, “\r”, “\n”,” “), ” “, $description);

 

这样一些小问题都得以完美解决,最后贴出完整代码:

<title><?php if (is_home() ) { ?>博客标题<?php } else {?><?php wp_title(”); ?> – 博客标题<?php } ?></title>
<?if (is_home()){
$description = “首页描述”;
$keywords = “首页关键词”;
} elseif (is_single()){
if ($post->post_excerpt) {
$description = $post->post_excerpt;
} else {
$description = substr(strip_tags($post->post_content),0,220);$description = str_replace(array(“\r\n”, “\r”, “\n”,” “), ” “, $description);
}
$keywords = “”;      
$tags = wp_get_post_tags($post->ID);
foreach ($tags as $tag ) {
$keywords = $keywords . $tag->name . “, “;
}$keywords = substr($keywords,0,-2);
} elseif(is_category()){
$description = category_description();
}
?>
<?php if (is_single()||is_home()) {?>
<meta name=“description” content=“<?=$description?>” />
<meta name=“keywords” content=“<?=$keywords?>” />
<?php } ?>
<?php if (is_page()):
$keywords = get_post_meta($post->ID, “keywords”, true);
if($keywords!=”") echo(“<meta name=\”keywords\” content=\”".$keywords.”\” />\n”);
$description = get_post_meta($post->ID, “description”, true);
if($description!=”") echo(“<meta name=\”description\” content=\”".$description.”\” />\n”);
endif;
?>

 

这样就可以完美的实现All in One SEO的功能了。

六月 23, 2010