telescope-122960_1280

Display Custom Fields In Your Search Results

Sometimes when you are setting up your search results page you don’t want to just use the_excerpt() to show your snippet. It’s not uncommon to use custom fields to store content that might be better suited to showing up.

In a lot of cases that content might be stored by your SEO plugin, say WordPress SEO. The problem is how do you use the description stored by that plugin, or a different custom field, for your snippet?

Setting Up Your page.php

This is going to take some customizing of your search results template. When setting up custom pages I normally route everything through page.php and use get_template_part to show what I need.

This is what the relevant parts of a typical page.php look like that are related to search:

Line 9 is the important one there. It’s where the search template is invoked. How get_template_part works is the two arguments are the two parts of the file name. That command would refer to content-search.php.

Setting Up Your Search Results Template

A very basic content-search.php file could look like this

But that’s just going to show the_excerpt() for everything, which isn’t what we’re after. We need to check for the existence of our custom field and use those instead, if they exist. A better content-search.php might look like this

This code checks for two different custom fields. yoast_wpseo_metadesc which is the meta description field from WordPress SEO plus featured-header-content which is a custom field used on a site I’m working on.

If one of those exist it will show the contents of that (after running it through wp_trim_words() to make the snippets a more uniform length) before just using the_excerpt().

This way you don’t have to just rely on WordPress to decide what to show in your search results and you can work just like a big search engine to try to get people to click on results after searching on your site.

Leave a Reply