0815

Du musst dich anmelden um Beiträge und Themen zu erstellen. Einloggen · Registrieren

Automatically Highlight Search Terms

Make things easy for people who are searching your site by applying some custom styling to the search terms that are displayed in the search results. A common way to display search terms is with a yellow background so that users can easily identify locations of the text that may apply to their query. It’s all about about usability, and improving the way search results are displayed on your site. Here’s how to do it:

First, replace the the_title() tag in your search.php file with the following:

<?php // highlight search terms in title
	$title = get_the_title();
	$keys  = explode(" ", $s);
	$title = preg_replace('/('.implode('|',$keys).')/iu','<span class="search-terms">\0</span>',$title);
	echo $title;
?>

This will setup styling for search terms located in the title of each result. Then, for the content, replace the the_excerpt() tag in your search.php file with the following:

<?php // highlight search terms in content
	$excerpt = get_the_excerpt();
	$keys  = explode(" ", $s);
	$excerpt = preg_replace('/('.implode('|',$keys).')/iu','<span class="search-terms">\0</span>',$excerpt);
	echo $excerpt;
?>

Finally, open your theme’s CSS file and add some custom styles for the search terms. A great way to highlight each term is to display it in bold text with yellow highlighting. Something like this:

span.search-terms { 
	background: yellow;
	font-weight: bold;
	}

That’s all there is to it! Go run a few searches to see it in action.

Source: Enhanced version of code provided by Yoast.com




0