没有插件如何获取突出显示的搜索字词?

#1 楼

将这两个函数添加到您的函数中。php

function search_excerpt_highlight() {
    $excerpt = get_the_excerpt();
    $keys = implode('|', explode(' ', get_search_query()));
    $excerpt = preg_replace('/(' . $keys .')/iu', '<strong class="search-highlight">
function search_content_highlight() {
        $content = get_the_content();
        $keys = implode('|', explode(' ', get_search_query()));
        $content = preg_replace('/(' . $keys .')/iu', '<strong class="search-highlight">
.search-highlight {
    background:#FFFF00  
    }
</strong>', $content); echo '<p>' . $content . '</p>'; }
</strong>', $excerpt); echo '<p>' . $excerpt . '</p>'; } function search_title_highlight() { $title = get_the_title(); $keys = implode('|', explode(' ', get_search_query())); $title = preg_replace('/(' . $keys .')/iu', '<strong class="search-highlight">q4312078q</strong>', $title); echo $title; }


编辑:

要在搜索结果中使用the_content,请使用以下函数:

q4312078q

在循环或search.php文件中,调用<?php search_title_highlight(); ?>而不是<?php the_title(); ?>,并使用<?php search_excerpt_highlight(); ?>而不是<?php the_excerpt(); ?>

在CSS中添加search-highlight该类将以黄色突出显示所有搜索到的单词。

q4312078q

评论


将preg_quote()应用于$ keys以防止正则表达式因括号或方括号之类的特殊字符而破裂。

– Geert
2011年5月1日7:09



在用户单击单曲并进入帖子后,突出显示搜索词该怎么办?然后,get_search_query()返回一个空字符串

–真·巴拉赞尼
2011年5月22日23:47

这些应该是the_excerpt和the_content的过滤器。无论如何:好的答案,但是@Geert的评论可以在:)中使用。

– kaiser
2012年10月13日,0:25

如果有搜索词,它将在我们的readmore链接中应用代码。

–user22614
2012年10月18日在7:20

是否也要替换readmore href中的文本?如何解决这个问题?

– Naveen
2014年1月13日12:58

#2 楼

上面的代码运行得很好,我运行了类似的代码,但是将标题和摘录绑定在一起。但是发现有人在搜索查询词的开头或结尾输入空格时会中断。

因此,我添加了以下行:
$keys = array_filter($keys);


// Add Bold to searched term
function highlight_results($text){
     if(is_search() && !is_admin()){
     $sr = get_query_var('s');
     $keys = explode(" ",$sr);
     $keys = array_filter($keys);
     $text = preg_replace('/('.implode('|', $keys) .')/iu', ''.$sr.'', $text);
     }
     return $text;
}
add_filter('the_excerpt', 'highlight_results');
add_filter('the_title', 'highlight_results');


希望这对其他人有帮助。

#3 楼

如果搜索词出现在HTML标记内,则上述解决方案会破坏页面。您应该使用类似以下内容的东西:

      $regEx = '\'(?!((<.*?)|(<a.*?)))(\b'. implode('|', $keys) . '\b)(?!(([^<>]*?)>)|([^>]*?</a>))\'iu';
      $text = preg_replace($regEx, '<strong class="search-highlight">q4312078q</strong>', $text);


评论


thanxs伴侣,您让我很开心:-)

– Agha Umair Ahmed
16年1月26日在11:56

#4 楼

结合使用过滤器的2个答案:

// Add class to searched terms
function highlight_results($text) {
    if (is_search() && !is_admin()) {
        $sr = get_query_var('s');
        $keys = explode(' ', $sr);
        $keys = array_filter($keys);
        $text = preg_replace('/('.implode('|', $keys) .')/iu', '<span class="search-highlight">
.search-highlight {
    background: #ffff94;
    padding: 0 2px;
}
</span>', $text); } return $text; } add_filter('the_excerpt', 'highlight_results'); add_filter('the_title', 'highlight_results');


然后在您的CSS中(例如):

q4312078q