Created
June 24, 2015 13:29
-
-
Save georgiecel/5ebc3bd4d7072ffbabd3 to your computer and use it in GitHub Desktop.
highlight the search term in the title & excerpt in WordPress – insert into functions.php; use <?php search_excerpt_highlight(n); ?> where n is excerpt word limit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function search_excerpt_highlight( $limit ) { | |
$excerpt = get_the_excerpt(); | |
$excerpt = explode(' ', get_the_excerpt(), $limit); | |
if ( count( $excerpt ) >= $limit ) { | |
array_pop( $excerpt ); | |
$excerpt = implode(' ', $excerpt); | |
} else { | |
$excerpt = implode(' ', $excerpt); | |
} | |
$excerpt = apply_filters( 'get_the_excerpt', $excerpt ); | |
$allowed_tags = '<p>,<br>,<mark>'; | |
$excerpt = strip_tags( $excerpt, $allowed_tags ); | |
$excerpt = preg_replace('`\[[^\]]*\]`', '', $excerpt); | |
$keys = implode('|', explode(' ', get_search_query())); | |
$excerpt = trim(preg_replace('/(' . $keys .')/iu', '<mark class="search-highlight">\0</mark>', $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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment