I’ve created two universal utility loops for surfacing related content, one by post type and one by post type with a shared taxonomy term. Create them once and drop them into any single post template. No need to create custom loops for simple queries. Each loop includes optional parameters for customization and has smart defaults that make sense for its use case. Both exclude the current post automatically and default to 3 results, with an optional $limit parameter if you need more.
If you’re looking for utility loops that fetch posts by ID, parent, or relationship field, check out Utility Loops for Fetching Posts by ID in Etch.
Related Posts by Post Type
Fetches recent posts of the same post type, excluding the current post.
Loop Configuration
Create a saved loop called Related Posts (relatedPosts)
$query_args = [
'post_type' => $post_type,
'posts_per_page' => $limit ?? 3,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'post__not_in' => [$post_id],
];
Common Use Cases
Related posts on a single post template:
{#loop relatedPosts($post_id: this.id, $post_type: this.post_type) as item}
<article class="post-card">
<h3 class="post-card__title">{item.title}</h3>
<a class="post-card__link" href="{item.permalink.relative}">Read more</a>
</article>
{/loop}
Related Posts by Post Type + Taxonomy
Fetches recent posts of the same post type that share a taxonomy term with the current post, excluding the current post.
Loop Configuration
Create a saved loop called Related Posts by Taxonomy (relatedPostsByTax)
$query_args = [
'post_type' => $post_type,
'posts_per_page' => $limit ?? 3,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'post__not_in' => [$post_id],
'tax_query' => [
[
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => [$term_id],
],
],
];
Common Use Cases
Related posts in the same category:
{#loop relatedPostsByTax($post_id: this.id, $post_type: this.post_type, $taxonomy: "category", $term_id: this.categories.at(0).id) as item}
<article class="post-card">
<h3 class="post-card__title">{item.title}</h3>
<a class="post-card__link" href="{item.permalink.relative}">Read more</a>
</article>
{/loop}
Related posts in the same custom taxonomy term, in this case we’ll use sector:
{#loop relatedPostsByTax($post_id: this.id, $post_type: this.post_type, $taxonomy: "sector", $term_id: this.sector.at(0).id) as item}
<article class="post-card">
<h3 class="post-card__title">{item.title}</h3>
<a class="post-card__link" href="{item.permalink.relative}">Read more</a>
</article>
{/loop}
Notes
$taxonomymust be quoted in the loop args (e.g.,"category","sector") so WordPress receives the literal string rather than the variable nametermsis wrapped as[$term_id]in the PHP becausetax_queryexpects an array, even for a single term.at(0).idpulls the term ID from the first term in the array- Both loops accept an optional
$limitparameter that defaults to3