Related posts by shared taxonomy terms
Query the posts that share the most tags with the current one, fall back to its category, and cache the result in a transient.
WordPressUtilitiesrelated-postswp-querytaxonomytransients
Code
How it works
What it solves
A good related-posts block keeps readers on the site, but the usual random category query shows weak matches. Ranking by the number of shared tags surfaces genuinely similar articles, and caching keeps the extra queries off busy pages.
How it works
The helper loads the current tag IDs, fetches up to four times the wanted number of candidates that share at least one tag, and scores each by the size of the tag intersection. Sorting descending yields the best matches. If fewer than the limit are found, remaining slots are filled from the same categories. The final ID list is stored in a transient for six hours and wiped on save_post.
The template function escapes titles and URLs.
Adapting it
Swap wp_get_post_tags for wp_get_object_terms with a custom taxonomy to support other post types. Add thumbnails by calling get_the_post_thumbnail. On sites with an object cache, delete only the affected key rather than running the SQL clean-up.
Pitfalls
- The bulk
DELETEis only suitable for small sites; with a persistent cache transients are not stored in the options table. no_found_rowsavoids an unneeded count query.- Per-candidate tag lookups cost queries; prime caches with
update_post_term_cachefor larger sets. - Exclude the current post, as the code does.
How to use it
Save as inc/related-posts.php and require it from functions.php.
Call acme_related_posts( 4 ); in single.php after the content.
Style .acme-related to match your theme.
Licence: GPL-2.0-or-later. This snippet comes from WordPress code and is GPL-2.0-or-later.