Can I get posts by using an array of tags using Jekyll?

Viewed 91

I'm working on a liquid script for my Jekyll website to retrieve related posts. I'd like to use the array of tags used for the current post (post.tags) to do a query that matches other posts on the site that also have one (or more) of those tags. Such as:

assign relatedPosts = site.posts | where 'tags', page.tags

However, in the documentation it only mentions passing in a string, not an array of strings? I would ideally like to accomplish this using the where operator (or something similar), instead of iterating through every post on the site.

1 Answers

You are correct that you can't supply an array for the where operator, as per the documentation, you can only pass a string there.

By the nature of your requirement, it looks like iterating through every post on the website is not something you can avoid, since basically you want to check all your posts for a couple of different tags.

One possible solution would be to iterate through your post tags first, then check that tag against all site post tags, something like this:

{% assign new_array = "" | split: "" %}
{% for tag in page.tags %}
    {% assign tag_found = site.posts | where "tags": tag %}
    {% assign new_array = new_array | concat: tag_found %}
{% endfor %}
OUTPUT: {{ new_array }}
Related