Using Movable Type Template Tags to Count Things

| 2 Comments | No TrackBacks |
For some things you want to display a count of, Movable Type provides handy template tags like <mt:entrycommentcount>, <mt:blogentrycount>, <mt:blogcategorycount> or even <mt:blogpagecount>.  But what if you wanted to count something else?  The number of authors whose name starts with a 'B'?  The number of comments containing a certain brand name?  The number of entry titles that have a word in them?
For situations like these, using the 'like' argument to the <mt:if> tag, in combination with some attributes of the <mt:var> tag can come in very handy.  Consider this code snippet:

<mt:var name="matches" value="0">

<mt:entries lastn="9999">
<mt:setvarblock name="thecounter"><mt:var name="__counter__"></mt:setvarblock>
<mt:if tag="entrytitle" like="Movable">
    <mt:var name="matches" op="+" value="1" setvar="matches">

Total number of entries: <mt:var name="thecounter"><br>
Number of enties with the word 'Movable' in the title: <mt:var name="matches">

Let's go over it line by line.  The first line sets the variable $matches to zero.  Then we loop over the past 9999 entries and we stick the value of the system variable __counter__ in a temporary variable named $thecounter each time we go through the loop.  This variable tells us where in the loop we are.  (This could be optimized further by only doing this the last time we go through the loop, but for the sake of simplicity it is not done here)

As soon as we find an entry where the title matches the string 'Movable' we add 1 to the value of the $matches and put the resulting value back into the $matches variable.

At the end, we display our results, which for this blog would look like this right now:

Total number of entries: 16
Number of enties with the word 'Movable' in the title: 10

(And after this particular entry has been published, it will be 11)

No TrackBacks

TrackBack URL:


hello!,I really like your writing so much! proportion we be in contact more approximately your post on AOL?
I need a specialist in this area to unravel my problem. Maybe that is you!
Having a look forward to see you.

I blog often and I really appreciate your content. This article has truly peaked my
interest. I am going to bookmark your website and keep checking for new information about once per week.

I opted in for your Feed too.

Leave a comment