Get number of all posts (including post count of children) inside a taxanomy

Hello there,
I am using following markdown to get list of taxanomies/categories with their post count.

<Loop type=taxonomy_term taxonomy=category>
 <a href="{Field url}"><Field title /></a> - <Field count /><br>

I get list of categories and post count as 0 because main parent categories have not been assigned any posts but sub-categories inside parent categories have posts. So I want to get number/count of posts in parent category including those post count in subcategories in post count field.

Hey Zakir! So if I understand correctly, your output is currently showing something like this:

Parent category - 0
First child category - 5
Second child category - 3

But you want the output to be more like this:

Parent category - 8
First child category - 5
Second child category - 3

Is that right? If so, I think I would probably approach this using the If loop exists syntax to check whether the current term has any children and if it does, add up all the posts belonging to those children.

<Loop type=taxonomy_term taxonomy=category>
  <a href="{Field url}"><Field title /></a> - 
  <If loop exists type=taxonomy_term taxonomy=category id="{Field children}">
      <Field count />+<Loop><Field count /><If not last>+</If></Loop>
    <Else />
    <Field count />
  <br />

What’s going on there is that for each item in the outer taxonomy term loop, we start by displaying the term title. Then we check whether a loop of the current term’s child terms exists. We’ll do this by passing the out loop’s children field to the id query parameter. If that loop does exist, then we need to do some math to add up the count of all the child terms. To do that we get the count of the current term, then we open the loop that we defined in our If statement (the If loop exists part of the docs explains all this). Then for each item in that child loop, we get its count and if it’s not the last item in the loop, we add a plus. This basically results in the following output that gets processed by the surrounding Math tag: parentcount+firstchildcount+secondchildcount+thirdchildcount.... If our child loop doesn’t exist, we have that little Else tag and then we just display the count of the current term.

One caveat with this approach is that if a post is added to multiple child categories, it’ll get counted multiple times toward the total. There would be ways of getting around that but that would get a bit complicated so I didn’t account for that in this template.

I’ve added this as an example to the documentation.


Yes thats exactly what I wanted to achieve. Thank You

1 Like