Limit Number of Blog Posts Shown with a Specific Tag

I would like to show the last 4 blog posts that have a specific tag. The following code will successfully render all the blog posts with a specific tag:

{%- for article in blog.articles -%}
{% if article.tags contains section.settings.article-tag %}

{%- render 'article-grid-item',
blog: blog,
article: article,
grid_item_width: 'medium-up--one-third',
per_row: '3',
image_size: section.settings.blog_image_size
-%}
{%endif%}
{%- endfor -%}

However… when I add a limit of 4, it only cycles through the last 4 blog posts and will return nothing if the last four blog posts do not contain the desired tag.

{%- for article in blog.articles limit:4 -%}

What can I do to cycle through all the blog posts until it finds the last 4 tagged with a specific tag?

Hi @sklieman ,

You try below code:

{% assign check = 1 %}
{%- for article in blog.articles -%}
{% if article.tags contains section.settings.article-tag and check < 5 %}
{% assign check = check | plus: 1 %}
{%- render 'article-grid-item',
blog: blog,
article: article,
grid_item_width: 'medium-up--one-third',
per_row: '3',
image_size: section.settings.blog_image_size
-%}
{%endif%}
{%- endfor -%}

If you feel like my answer is helpful, please mark it as a SOLUTION. Let me know if you have any further questions.

1 Like

Hi,

I have used above code but it returns 2 data but it has 40 post.

Please check below my code:

{%- for article in blogs.blog.articles -%}
{% if article.tags contains ‘diffusers’ %}

{{ article.title }}

{%endif%} {%- endfor -%}

Why other post are not showing?

1 Like

Hi,

We can get articles by specific tag.

Below is my code:

{% assign blog_handles = “blog” | split: “,” %}
{% assign blog_tag = “Featured_Post” %}

{% for handle in blog_handles %}
{% paginate blogs[handle].articles by 100 %}
{% for article in blogs[handle].articles %}
{% if article.tags contains blog_tag %}

{{ article.title }}

{%endif%} {% endfor %} {% endpaginate %} {% endfor %}

Above code is working for me.

1 Like

Hi, I’m a newbie and and confused on how to get this code to work. Please help. If I’m trying to pull posts from my blog, “First Fridays” and from the tag “Art and Soul”, where and how would I need to input that info in the code above. Is it case sensitive, do they need underscores between words? I can’t get it to work. And do I just paste this into a Custom Liquid section in a page where I want these posts to show up? Thanks so much.

1 Like