首先要说的是,本站使用的SEO方法就是出自于下面这篇文章。

对Wordpress进行SEO的方法有很多,最简单的就是安装相关的SEO插件。但是相信很多人和我一样,不喜欢使用插件,反而更加相信手写的PHP代码。所以这里就分享一下不使用插件进行SEO的方法。

首先明确一下会遇到并解决的问题:

1. 默认的title里文字前面出现空格。

2. 使用foreach循环后的字符串keywords标签里最后一个关键词后面还有一个逗号。

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

下面就分步解释如何进行进行具体的代码优化。

一. WordPress 页面标题的优化。

<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的自定义域功能实现。

三. 遇到问题的解决。

A. 解决keywords最后一个关键词后出现逗号的方法:
在tag循环外加代码:$keywords = substr($keywords,0,-2);

B. 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 = “首页关键词”;
} else if (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);
} else if (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;
?>

所属栏目: 营销&技术

请评论


创业故事·由创业路上的你我来分享!