How to count the number of posts within taxonomy terms

I was actually struggling with the title – what I wanted to write about was how to count posts within taxonomy terms. 🙂 Let’s say we have taxonomy “cars”, while inside “cars” we have “BMW” term. What we want is a function which counts the number of BMWs. This is the idea I came up with – it is using the get_term WordPress function. What we need is the ID for BMW term, something you can obtain by hovering over this term within WordPress dashboard.

Here is the function:

The first thing we do here is getting our $term using get_term function, where 26 is BMW’s ID and cars is taxonomy name. After that we use PHP count function and store this value into $counter variable. This variable holds the number of posts assigned to term with ID 26.