3
votes

I have a Jekyll site built and for the posts, I have 3 sub-categories.

These categories are: blog examples tips

In each one of these categories I also have sub-categories for html, css and js.

In each post I have front-matter and a categories tag which looks like this as an example:


categories: - blog

- html

I would like to create a loop that outputs the post count for each category. So if under blogs I have 2 posts in each sub-category:

  • blogs
    • HTML
    • html-post1.md
    • html-post2.md
    • css
    • css-post1.md
    • css-post2.md
    • js
    • js-post1.md
    • js-post2.md

How can I loop over this to just display the count instead of outputting each post?

2
I just submitted an answer but I'm not sure if it is what you need. Are you trying to show all categories and their counts by looping over categories? My solution might work but it may need to be slightly modified. Please share any code that you currently have and I can try to edit my answer.briancaffey
I am trying to show a category count only if it exists as part of two categories. For example I want to show a count for all html posts if part of blogs. You can see my repo here: github.com/lmarzy/openbracketmarzy

2 Answers

5
votes

You can loop directly over your site's categories like this:

<ul>
{% for cat in site.categories %}
    <li>{{ cat[0] }} ({{ cat[1].size }})</li>
{% endfor %}
</ul>

cat[0] is the category's name.
cat[1] is an array of all posts with that category, so cat[1].size is the number of posts.

The resulting HTML will look like this:

<ul>
    <li>HTML (2)</li>
    <li>css (2)</li>
    <li>js (2)</li>
</ul>

Note that the list of categories is unordered by default.
If you want to order it by name or post count, the solution is slightly more complicated.

2
votes

For each category you could include a count like this:

  {% assign total = 0 %}
  {% for post in site.posts %}
     {% if post.category == "some_category" %}
      {% assign total = total | plus: 1 %}
     {% endif %}
  {% endfor %}