Highlight terms in the search results

Marko Krstić
27 Dec 2019

PHP in Function

<?php 
function search_excerpt_highlight() {
    $excerpt = get_the_excerpt();
    $keys = implode('|', explode(' ', get_search_query()));
    $excerpt = preg_replace('/(' . $keys .')/iu', '<strong class="search-highlight">\0</strong>', $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;
}
?>

PHP in codeblock

<?php
$search_query = get_search_query();
// WP_Query arguments
$args = array(
    'post_type'              => array( 'post', 'gesamtprojekt', 'startseite', 'teilprojekte', 'umwelt', 'service' ),
    's'                      => $search_query,
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        // do something
    ?>
		<div class="search-link">
			<h2><?php search_title_highlight(); ?></h2>
			<?php search_excerpt_highlight(); ?>
            <a href="<?php the_permalink(); ?>" >Seite aufrufen</a>
		</div>
	<?php
      
    }
} else {
    echo '<h2>Nichts gefunden für: '.$search_query.'</h2>';
}
// Restore original Post Data
wp_reset_postdata();
?>

CSS

.search-highlight {
   	background:#FFFF00;
}

Was this article helpful?

Tags

Categories

Never miss new post again

Subscribe and get list of new posts in your inbox

Click to Copy