dongtuojuan8998 2018-12-12 05:23
浏览 69
已采纳

突出显示搜索字词

Is there a way we can set up the highlight functionality to only highlight the words on the page if it matches the exact sentence?

If I try searching for "how do i insure a house", the search results look funky and the highlight functionality spaces out the words.

Output:

enter image description here

This is my code:

  function highlight_search_term_placeholders() {
    static $iter = 0;
    $ret = "|##{$iter}##|";
    $iter++;
    return $ret;
  }
  function highlight_search_term_cb() {
    static $iter = 0;
    $ret = "##{$iter}##";
    $iter++;
    return $ret;
  }
  function highlight_search_term($text){
    if(is_search() && !is_admin()){
      $keys = implode('|', explode(' ', get_search_query()));
      $pattern = '/<[^>].*?>/i';
      preg_match_all($pattern,$text,$matches);
      $placeholders = array();
      foreach ($matches[0] as $v) {
        $placeholders[] = highlight_search_term_placeholders();
      }
      $text = preg_replace_callback($pattern,'highlight_search_term_cb',$text);
      $pattern2 = '/(' . $keys .')/iu';
      $text = preg_replace($pattern2, ' <span class="search-term">\1</span> ', $text);
      $text = preg_replace($placeholders,$matches[0],$text);
    }
    return $text;
  }
  add_filter('the_excerpt', 'highlight_search_term');



function highlight_results_css() {
    ?>
    <style>
        .search-term { background-color:#FF0; }
    </style>
    <?php
}
add_action('wp_head','highlight_results_css');
  • 写回答

1条回答 默认 最新

  • dousi6192 2018-12-12 05:26
    关注

    Quick'n'dirty: replace

    $keys = implode('|', explode(' ', get_search_query()));
    

    with

    $keys = get_search_query();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分