From 049823aaa55ed284337e3c423ddd9ceae18fa3fa Mon Sep 17 00:00:00 2001 From: Laury GvR Date: Thu, 18 Jun 2015 11:46:29 -0400 Subject: [PATCH] Contextual/highlight search added. --- root/functions.php | 26 ++++++++++++++++++++ root/search.php | 59 +++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 84 insertions(+), 1 deletion(-) diff --git a/root/functions.php b/root/functions.php index de3c741..269793f 100644 --- a/root/functions.php +++ b/root/functions.php @@ -204,4 +204,30 @@ function glm_side_menu() { add_action('wp_enqueue_scripts', 'glm_site_scripts'); + + +// +function mytheme_init() { + remove_action('thematic_searchloop', 'thematic_search_loop'); +} + +add_action('init', 'mytheme_init', 10); + +function mytheme_search_loop() { + while ( have_posts() ) : the_post(); ?> + +
+ +
+ + +
+ +
+ + ?> diff --git a/root/search.php b/root/search.php index 9a03e76..3fef015 100644 --- a/root/search.php +++ b/root/search.php @@ -14,7 +14,64 @@

Posted on - + + + + @'), array(' ', "\n"), apply_filters('the_content', $post->post_content))) : ''); + + // Search content for terms + $terms = $wp_query->query_vars['search_terms']; + if ( preg_match_all('/'.str_replace('/', '\/', join('|', $terms)).'/i', $content, $matches, PREG_OFFSET_CAPTURE) ) { + $padding = max($min_padding, $max_length / (2*count($matches[0]))); + + // Construct extract containing context for each term + $output = ''; + $last_offset = 0; + foreach ( $matches[0] as $match ) { + list($string, $offset) = $match; + $start = $offset-$padding; + $end = $offset+strlen($string)+$padding; + // Preserve whole words + while ( $start > 1 && preg_match('/[A-Za-z0-9\'"-]/', $content{$start-1}) ) $start--; + while ( $end < strlen($content)-1 && preg_match('/[A-Za-z0-9\'"-]/', $content{$end}) ) $end++; + $start = max($start, $last_offset); + $context = substr($content, $start, $end-$start); + if ( $start > $last_offset ) $context = '...'.$context; + $output .= $context; + $last_offset = $end; + } + + if ( $last_offset != strlen($content)-1 ) $output .= '...'; + } else { + $output = $content; + } + + if ( strlen($output) > $max_length ) { + $end = $max_length-3; + while ( $end > 1 && preg_match('/[A-Za-z0-9\'"-]/', $output{$end-1}) ) $end--; + $output = substr($output, 0, $end) . '...'; + } + + // Highlight matches + $context = nl2br(preg_replace('/'.str_replace('/', '\/', join('|', $terms)).'/i', '$0', $output)); + ?> + +

+ +

+

+ Read this entry +

+ + +