Highlight the search terms in results in WordPress
Highlight the search terms in results in WordPress
Use this code in theme’s function.php, and use search_excerpt_highlight() instead of the_excerpt() from where the search result coming.
function search_excerpt_highlight() {
$excerpt = get_the_excerpt();
$keys = implode('|', explode(' ', get_search_query()));
$excerpt = preg_replace('/(' . $keys .')/iu', '<span class="search-highlight"></span>', $excerpt);
echo '<p>' . $excerpt . '</p>';
}and use this in CSS file or customize your style.
.search-highlight{
font-weight:bold;
}
But this can break you read-more link, if the search term exists in that.
So please use this code:
function search_excerpt_highlight() {
$excerpt = get_the_excerpt();
$keys = implode('|', explode(' ', get_search_query()));
$excerpt = preg_replace('/(' . $keys .')/iu', '<span></span>', $excerpt);
echo '<p>' . $excerpt . '…' . supralegal_read_more_link() . '</p>';
}
function supralegal_auto_excerpt_more( $more ) {
return '';
}
add_filter( 'excerpt_more', 'supralegal_auto_excerpt_more' );
function supralegal_read_more_link() {
return ' <a href="'. esc_url( get_permalink() ) . '">' . __( 'Read more', 'supralegal' ) . '</a>';
}
in supralegal_read_more_link() function write your read-more link code.

Post a Comment