您的位置:首页 > 编程语言

WordPress搜索结果中增加关键词高亮显示代码

2014-01-21 00:00 736 查看
在多梦网络的博客上看到了这个效果代码,所以就拿过来试了一下,感觉还不错。有需要的朋友也可以试试看。
把以下代码加入WordPress主题目录下的搜索模板文件(一般是search.php)中的主循环中
<?php
$title = get_the_title();
//300是摘要字符数,......是结束符号。
$content = mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 300,"......"); 
$keys = explode(" ",$s);
$title = preg_replace('/('.implode('|', $keys) .')/iu','<strong style="color:#953b39;">\0</strong>',$title);
$content = preg_replace('/('.implode('|', $keys) .')/iu','<strong style="color:#953b39;">\0</strong>',$content); 
?>


然后在需要显示标题的地方使用以下代码显示
<?php echo $title; ?>
在需要显示摘要的地方使用以下代码
<?php echo $content;?>
应该是很简单的。代码加入search.php之后应该就会有效果。记住要把这些代码放在一个循环中。
不要把主代码放在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 style="color: #953b39;">\0</strong>',$title); 
$content = preg_replace('/('.implode('|', $keys) .')/iu','<strong style="color: #953b39;">\0</strong>',$content); 
}?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: