|
<?php |
|
/** |
|
* Hook to highlight the title when returning search results |
|
*/ |
|
function moveiq_title_highlight_results($text){ |
|
if( is_search() ){ |
|
$sr = get_query_var('s'); |
|
|
|
return moveiq_highlight_search_terms( $sr, $text, true ); |
|
} |
|
|
|
return $text; |
|
} |
|
|
|
add_filter('the_title', 'moveiq_title_highlight_results'); |
|
|
|
/** |
|
* Hook to filter the excerpt functions |
|
* This hook trims the excerpt to the $length, and also highlights the text if |
|
* search term was found in the content. If the search term was found in the middle |
|
* of the content, then it is trimmed in the context, not from the beginning of text |
|
*/ |
|
function moveiq_excerpt_highlight_results(){ |
|
|
|
global $post; |
|
$length = 250; |
|
|
|
// Set up search var |
|
$s = is_search() ? get_query_var( 's', false ) : false; |
|
|
|
// If post has a manual excerpt |
|
if ( $post->post_excerpt ) { |
|
if ( $s ) { |
|
return moveiq_highlight_search_terms( $s, $post->post_excerpt, true ); |
|
} |
|
|
|
return $post->post_excerpt; |
|
} |
|
|
|
// hack to deal with gutenberg modules and html markup |
|
$content = str_replace( ' ', ' ', $post->post_content ); |
|
$content = wp_trim_words( $content, 99999, '' ); |
|
|
|
// If post is shorter than our excerpt length |
|
if ( strlen( $content ) <= $length ) { |
|
if ( $s ) { |
|
return moveiq_highlight_search_terms( $s, $content, true ); |
|
} |
|
|
|
return $content; |
|
} |
|
|
|
// If search string is found in the content |
|
if ( $s ) { |
|
$content = moveiq_highlight_search_terms( $s, $content ); |
|
|
|
$position = strpos( $content, '%b' ); |
|
|
|
if ( $position - 130 <= 0 ) { |
|
$excerpt = substr( $content, 0, $length + 8 ); |
|
$excerpt = substr( $excerpt, 0, strrpos( $excerpt, " " ) ) . '...'; |
|
} else { |
|
$excerpt = substr( $content, $position - 130, $length + 8 ); |
|
$excerpt = '...' . substr( $excerpt, strpos( $excerpt, " " ), strlen( $excerpt ) ); |
|
$excerpt = substr( $excerpt, 0, strrpos( $excerpt, " " ) ) . '...'; |
|
} |
|
|
|
$excerpt = str_replace( ['%b', '%e'], [ "<span class='search-highlight'>", "</span>" ], $excerpt ); |
|
} |
|
// If not |
|
else { |
|
$excerpt = substr( $content, 0, $length ); |
|
$excerpt = substr( $excerpt, 0, strrpos( $excerpt, " " ) ) . '...'; |
|
} |
|
|
|
return $excerpt; |
|
} |
|
|
|
add_filter( 'get_the_excerpt', 'moveiq_excerpt_highlight_results' ); |