4

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. Jan 30, 2018 at 20:40
  • 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/openbracket
    – marzy
    Feb 1, 2018 at 18:17

2 Answers 2

6

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.

1
  • Thank you for the quick response. This almost works but let me explain a little more. So under _posts I have the following directory: blogs examples tips In each one of these directories I may have a sub directory such as: html css js Then in each .md file I have the following: --- categories: - blog - html --- What I want to do is show the count for say just the html posts when it's a blog, I may have another html category but in say tips and I dont want the count to display for this. GitHub link here if it helps: github.com/lmarzy/openbracket
    – marzy
    Jan 31, 2018 at 20:16
3

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 %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.