突出显示在 WordPress 搜索中搜索的单词

ton*_*nyf 4 wordpress

我正在使用内置的 WordPress search.php 例程,是否可以在检索到的搜索结果的上下文中突出显示搜索到的单词?

例如,如果我输入“产品”,任何返回此匹配单词的页面都会向用户突出显示。

谢谢。

Chr*_*s_O 5

您可以将以下函数添加到functions.php 中,该函数将在结果中突出显示搜索的术语。

/* Search Highlighting ********************************************/
// This highlights search terms in both titles, excerpts and content

function search_excerpt_highlight() {
 $excerpt = get_the_excerpt();
 $keys = implode('|', explode(' ', get_search_query()));
 $excerpt = preg_replace('/(' . $keys .')/iu', '<strong class="search-highlight">\0</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">\0</strong>', $title);

 echo $title;
}
Run Code Online (Sandbox Code Playgroud)

要使用此功能,必须将其添加到您的存档循环中:

<?php if (is_search() ) { 

    search_excerpt_highlight(); } ?>
Run Code Online (Sandbox Code Playgroud)