highlight query in search result more precisley
This commit is contained in:
parent
ef9644c8d7
commit
9423a7bff0
1 changed files with 48 additions and 12 deletions
|
|
@ -431,22 +431,58 @@ add_action( 'widgets_init', 'kit_widgets_init' );
|
|||
|
||||
# Highlight query in search results
|
||||
|
||||
function limit_text($text, $limit) {
|
||||
if (str_word_count($text, 0) > $limit) {
|
||||
$words = str_word_count($text, 2);
|
||||
$pos = array_keys($words);
|
||||
$text = substr($text, 0, $pos[$limit]);
|
||||
function generate_excerpt($text, $query, $length) {
|
||||
|
||||
$words = explode(' ', $text);
|
||||
$total_words = count($words);
|
||||
|
||||
if ($total_words > $length) {
|
||||
|
||||
$queryLow = array_map('strtolower', $query);
|
||||
$wordsLow = array_map('strtolower', $words);
|
||||
|
||||
for ($i=0; $i <= $total_words; $i++) {
|
||||
|
||||
foreach ($queryLow as $queryItem) {
|
||||
|
||||
if (preg_match("/\b$queryItem\b/", $wordsLow[$i])) {
|
||||
$posFound = $i;
|
||||
break;
|
||||
}
|
||||
return $text;
|
||||
}
|
||||
|
||||
if ($posFound) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ($i > ($length+($length/2))) {
|
||||
$i = $i - ($length/2);
|
||||
} else {
|
||||
$i = 0;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
$cutword = array_splice($words,$i,$length);
|
||||
$excerpt = implode(' ', $cutword);
|
||||
|
||||
$keys = implode('|', $query);
|
||||
$excerpt = preg_replace('/(' . $keys .')/iu', '<strong class="tx-indexedsearch-redMarkup">\0</strong>', $excerpt);
|
||||
$excerptRet = '<p>';
|
||||
if ($i !== 0) {
|
||||
$excerptRet .= '... ';
|
||||
}
|
||||
$excerptRet .= $excerpt . ' ...</p>';
|
||||
|
||||
return $excerptRet;
|
||||
}
|
||||
|
||||
function search_excerpt_highlight() {
|
||||
|
||||
$excerpt = wp_strip_all_tags( get_the_content() );
|
||||
$excerpt = limit_text( $excerpt, 32);
|
||||
$length = 32;
|
||||
$text = wp_strip_all_tags( get_the_content() );
|
||||
$query = explode(' ', get_search_query());
|
||||
|
||||
$keys = implode('|', explode(' ', get_search_query()));
|
||||
$excerpt = preg_replace('/(' . $keys .')/iu', '<strong class="tx-indexedsearch-redMarkup">\0</strong>', $excerpt);
|
||||
|
||||
echo '<p>... ' . $excerpt . ' ...</p>';
|
||||
echo generate_excerpt($text, $query, $length);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue