存档

文章标签 ‘关键词’

Wordpress关键词高亮

2009年10月3日 admin 没有评论

在搜索结果页面结果中显示关键词,或者对搜索引擎带来的用户显示欢迎语和操作提示,是一个能有效提高网站易用性的方法。wordpress下关键字高亮工具有很多,有searchhilight, wp landing sites, wp-hightlights等,其中wp landing sites可以提供欢迎语,使用方法如下:

第一步,修改你主题下的single.php和index.php,加入以下内容
<?php if (ls_getinfo('isref')) : ?>
<p class='landingsites'>欢迎来自 <?php ls_getinfo('referrer'); ?> 的朋友! 如果您是第一次来到这里, 推荐您通过
<a href='/feed' target='_blank'>RSS feed</a> 订阅我的博客!</p>
<div class="hello">您所搜索的关键词为: <strong><?php ls_getinfo('terms'); ?></strong></div>
<?php endif; ?>

第二步,在css中添加

.landingsites {
background-color:#FFFEC6;
border:thin dashed #CFCFCF;
color:#333333;
font-size:12px;
margin:3px 0 10px;
padding:6px;
}

第三步是修改插件中的landingsites.php中的searchengine数组中加入支持百度和中文谷歌的支持,

'google.cn' => 'q',
'baidu.com' => 'wd',

中文转码修改:
function ls_get_terms($d)函数最后返回return $terms;之前加上如下代码:

if (!seems_utf8($terms)){
$terms=iconv("GBK", "UTF-8", $terms);
}

这样你就可以在百度和google中看一下效果了。
要继续优化,可以考虑以下几点:

1. 在404页面中添加相关文章,这样即使是碰到google来的断链,用户也会找到些有用的东西:
<?php if (ls_getinfo('isref')) : ?>
<h2><?php ls_getinfo('terms'); ?></h2>
<p>欢迎来自 <?php ls_getinfo('referrer'); ?> 的朋友! 您所找的页面不存在,但是你搜索的关键词:<i><?php ls_getinfo('terms'); ?></i>. 有以下主题或许您也感兴趣:</p>
<ul>
<?php ls_related(5, 10, '<li>', '</li>', '', '', false, false); ?>
</ul>
<?php endif; ?>

2. 加粗或者高亮关键词:

function ls_terms_filter($content){
// Did we come from a search engine?
$referer = ls_get_refer();//取来源域名
$output = ;
$delimiter = ls_get_delim($referer);//看是否在list里面
if($delimiter)
{
$terms = ls_get_terms($delimiter);//取关键字串
$terms= array_unique(preg_split(/[\s,]+/, $terms));//转换为数组
$contentarr = preg_split(/(<.*>)/U, $content, -1, PREG_SPLIT_DELIM_CAPTURE); // capture the tags as well as in between
$stop = count($contentarr);// loop stuff
for ($i = 0; $i < $stop; $i++) {
$content = $contentarr[$i];
if ((strlen($content) > 0) && (< != $content{0})) { // If it’s not a tag
foreach ($terms as $term) {
if (strlen($term)>1)//避免关键字太短的情况
$content=eregi_replace(($term),<b>\\1</b>, $content);
}
}
$output .= $content;
}
return $output;
} else{
return $content;
}
}

增加了上述的function,对内容里面的关键字进行加粗处理
增加了2个filter

add_filter(the_content, ls_terms_filter);
add_filter(comment_text, ls_terms_filter);
如果只需要高亮关键词而不需要欢迎语可以用search_hilite插件。但是这两个方法在使用super  cache时都会出问题,比较好的highlight是纯php方案,如Js的搜索引擎关键字高亮工具Search Engine Keyword Highlight,这方面的wp插件可以用这个wp-hightlight插件。需要注意的是这个插件的最后有个后门钩子,需要去掉.
这个JS之前对中文和百度是不生效的,参照了这篇文章做了修改,现在百度和中文都可以使用了:

http://www.aiview.com/2005/08/highlight_keywords_with_javascript.html

分类: 技术分享 标签: ,