WordPress教程

WordPress搜索关键词高亮两种方法

阿里云


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

方法一

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

也想出现在这里?联系我们
创客主机
  1. <?php
  2. $s = trim(get_search_query()) ? trim(get_search_query()) : 0;
  3. $title = get_the_title();
  4. //300是摘要字符数,......是结束符号。
  5. $content = mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 300,"......"); 
  6. if($s){$keys = explode(" ",$s); 
  7. $title = preg_replace('/('.implode('|', $keys) .')/iu','<strong style="color: #953b39;">\0</strong>',$title); 
  8. $content = preg_replace('/('.implode('|', $keys) .')/iu','<strong style="color: #953b39;">\0</strong>',$content); 
  9. }?>

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

  1. <?php echo $title; ?>

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

  1. <?php echo $content;?>

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

方法二

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

  1. function search_word_replace($buffer){
  2.     if(is_search()){
  3.         $arr = explode(" ", get_search_query());
  4.         $arr = array_unique($arr);
  5.         foreach($arr as $v)
  6.             if($v)
  7.                 $buffer = preg_replace("/(".$v.")/i", "<span style=\"background-color:#ff0;\"><strong>$1</strong></span>", $buffer);
  8.     }
  9.     return $buffer;
  10. }
  11. add_filter("the_title", "search_word_replace", 200);
  12. add_filter("the_excerpt", "search_word_replace", 200);
  13. add_filter("the_content", "search_word_replace", 200);

WordPress 搜索关键词高亮两种方法

已有 445 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!