Highlight a search term and show its location in the excerpt

Sometimes a client will want the search term in the results page to show the first occurrence of the searched word in the content of that page. Here is some basic functionality to do that.

 

Add WordPress Stop Words

Sometimes a client will want to prevent certain words from being included in or affecting the search results. In order to remove these words from the search query we can just add them to the WP_Query stopwords like so:

 

Include Taxonomy Links in Search Results

By default WordPress (and many search plugins) will only find Posts associated with a category. So even if you search the exact category name, only posts which have that category will be listed.

We had a client that needed the category pages to be listed as well. Here is the solution I came up with to resolve that problem.

Step 1

Hook into our pre_get_posts and search our taxonomies with some custom queries.

 

Step 2

Attach the terms we found to our search results

 

Step 3

No code here, but just be aware that on your search page your $post object in the loop will not have “post_title” or other default post values. So you will need to check if the “$post” you are handling is a term and then set it up correctly.

Good luck!