Get blog tags only relevant to current pagination page

Hi

I’ve setup a tag filter that works well when all articles are in view on the listing page.

{% set filter_tags = blog_tags('default') %}
{% for item in filter_tags %}
 <button class="button" data-filter=".{{ item.name | lower | replace(" ", "-") }}">{{ item.name }}</button>
{% endfor %}

The only problem is that when the listing is paginated it shows tags that may not be present in the displayed articles, e.g. articles on page 2 in the range 20-30 may not use all the tags.

Is it possible to adapt this to only call tags that are used on the posts shown in the current paginated view?

Thank you for any help!

Hello @DM2
Filter the tags based on the posts that are currently being displayed. Modify your code to achieve this.

{% set filter_tags = [] %}
{% for post in blog_posts %}
 {% for tag in post.tags %}
 {% if filter_tags contains tag %}
 {% continue %}
 {% endif %}
 {% set filter_tags = filter_tags | push(tag) %}
 {% endfor %}
{% endfor %}

{% for item in filter_tags %}
 <button class="button" data-filter=".{{ item.name | lower | replace(" ", "-") }}">{{ item.name }}</button>
{% endfor %}

I assume that you have a variable blog_posts that contains the posts being displayed on the current pagination page. You can adjust this variable based on your actual implementation.

The code iterates over each post and checks its tags. If a tag is already in the filter_tags list, it skips it. Otherwise, it adds the tag to the filter_tags list using the push filter. This way, only unique tags from the current paginated view will be displayed. Make sure to replace blog_posts with your actual variable name containing the posts, and adjust the code according to your specific implementation if needed. With this modification, the tags displayed will be relevant to the posts shown on the current paginated view.

Thank you! I will take a look at that.