diff --git a/kit/functions.php b/kit/functions.php index efc50aa..7ba51a9 100644 --- a/kit/functions.php +++ b/kit/functions.php @@ -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; + } + } + + 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', '\0', $excerpt); + $excerptRet = '

'; + if ($i !== 0) { + $excerptRet .= '... '; } - return $text; + $excerptRet .= $excerpt . ' ...

'; + + 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', '\0', $excerpt); - - echo '

... ' . $excerpt . ' ...

'; + echo generate_excerpt($text, $query, $length); }