WordPress实现搜索关键词高亮方法有哪些?

作者:30115776@qq.com

WordPress实现搜索关键词高亮方法有哪些?WordPress搜索关键词高亮显示是一个非常实用的技巧,将搜索结果中的关键词高亮标出使用户一目了然,十分有利于用户体验。

方法一

把以下代码加入WordPress主题目录下的搜索模板文件(一般是search.php)中的主循环中:

<?php

$s = trim(get_search_query()) ? trim(get_search_query()) : 0;

$title = get_the_title();

//300是摘要字符数,……是结束符号。

$content = mb_strimwidth(strip_tags(apply_filters(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’the_content\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’, $post->post_content)), 0, 300,\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”……\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”);

if($s){$keys = explode(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\” \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”,$s);

$title = preg_replace(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’/(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’.implode(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’|\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’, $keys) .\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’)/iu\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’,\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'<strong>\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\0</strong>\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’,$title);

$content = preg_replace(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’/(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’.implode(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’|\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’, $keys) .\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’)/iu\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’,\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'<strong>\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\0</strong>\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’,$content);

}?>

然后在需要显示标题的地方使用以下代码显示:

<?php echo $title; ?>

在需要显示摘要的地方使用以下代码:

<?php echo $content;?>

应该是很简单的。代码加入search.php之后应该就会有效果。记住要把这些代码放在一个循环中。不要把主代码放在search.php中,而下面的显示标题和内容的代码放在引入的列表文件。

方法二

实现高亮显示WordPress搜索关键词的方法有多种,有的是在搜索页面中修改,有的需要在header中修改,这里介绍一个比较简单实用的方法,将以下代码添加到主题目录的functions.php中即可,显示的样式还可以自定义:

function search_word_replace($buffer){

if(is_search()){

$arr = explode(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\” \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”, get_search_query());

$arr = array_unique($arr);

foreach($arr as $v)

if($v)

$buffer = preg_replace(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”/(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”.$v.\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”)/i\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”<span style=\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”background-color:#ff0;\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”><strong>$1</strong></span>\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”, $buffer);

}

return $buffer;

}

add_filter(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”the_title\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”search_word_replace\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”, 200);

add_filter(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”the_excerpt\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”search_word_replace\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”, 200);

add_filter(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”the_content\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”search_word_replace\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”, 200);

发表评论