Created
November 5, 2017 04:32
-
-
Save jomurgel/eb7edae0e8f8aadad6a5b9da28545c49 to your computer and use it in GitHub Desktop.
Highlight searched term in content
This file contains 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
<?php | |
function get_highlighted_content( $args = array() ) { | |
// Setup defaults. | |
$defaults = array( | |
'content' => get_the_title(), | |
); | |
// Parse args. | |
$args = wp_parse_args( $args, $defaults ); | |
// Get queried term and force lowercase. | |
$search_query = strtolower( get_search_query() ); | |
// Set list of articles. | |
$articles = array( 'in', 'at', 'a', 'an', 'the', 'of', 'and', 'to', 'for', 'into' ); | |
// Replace list of articles with nothing — does check for exact match. | |
$search_query = preg_replace( '/\b(' . implode( '|', $articles ) . ')\b/', '', $search_query ); | |
// Get content text. | |
$content = $args['content']; | |
// Split string for loop below by spaces. | |
if ( ! is_array( $search_query ) ) { | |
$search_query = preg_split( '/ /', $search_query, -1, PREG_SPLIT_NO_EMPTY ); | |
} | |
// Define Pattern and Separator. | |
$pattern = '#\\b(\\w*)('; | |
$sep = ''; | |
// Loop throug each word in search query string. | |
foreach ( $search_query as $word ) { | |
$pattern .= $sep . preg_quote( ' ' . $word, '' ); | |
$sep = '|'; | |
} | |
// Capture word/word-characters after foreach. | |
$pattern .= ')(\\w*)\\b#i'; | |
// Using \1 \2 \3 at relevant places. Make it so. | |
return preg_replace( $pattern, '\\1<strong>\\2</strong>\\3', $content ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment