We use SearchWP on almost all the websites we build. It provides search results based on relevancy rather than recency; indexes more attributes like categories, tags, and custom fields; and includes detailed reporting for on-site searches.
It’s also a great tool for related posts. Instead of showing recent posts in the same category or tag and hoping they are related to the current post, you can ask SearchWP for content that is actually related.
The Related Content extension adds a metabox for controlling the keywords used. By default it uses the current post’s title as the keyword, but you can modify it to include any keywords you like. It also displays live search results based on those keywords:
This metabox appears on all post types by default, but you can use
searchwp_related_excluded_post_types to exclude, or include it on specific post types.
Displaying Related Posts
There are a few different ways to display the related posts:
- SearchWP can auto-append them to the bottom of your posts using their template.
- SearchWP can auto-append them to the bottom of your posts using your template, defined in
your-theme/searchwp-related/related.php. Here’s more information on building your own template for their template loader.
- You define where they appear in your theme and use their template loader, either with their template or your custom template. Here’s a code example.
- You define where they appear in your theme and use your own custom query. This gives you the most flexibility over the query and display.
I like to use #4 and then add a fallback in case SearchWP is ever disabled, or if the keyword search delivers less results than we want displayed.
I created a
be_get_related_posts() function that queries for related using SearchWP Related. If we need more posts, we then query for recent posts in the same primary category using ea_first_term().
Then I create a function to display the related posts. We use template parts for reusable blocks of code like post summaries. This allows us to use the same format for listings on archive pages, post listings on landing pages, and related posts on single posts.