Archive tree with article counts

Someone on TXP Forum asked for a simple way to construct a tree of articles sorted by year/month, with article counts, like this:

…and so on. trenc came out with an elegant solution for the tree, presented below with small modifications. We have added empty span placeholders for counts and put the tree into the archive variable for further needs.

The code

<txp:variable name="archive">
<txp:article_custom sort="Posted desc" limit="999">

	<txp:variable name="year" value='<txp:if_different><txp:posted format="%Y" /></txp:if_different>' />
	<txp:variable name="month" value='<txp:if_different><txp:posted format="%Y-%m" /></txp:if_different>' />

		<li><txp:posted format="%Y" /> (<span></span>)<ul>
		<li><txp:posted format="%b" /> (<span></span>)<ul>
	<txp:else />
		<txp:if_variable name="month" value=""><txp:else />
			<txp:if_variable name="year" value=""><txp:else />
				<li><txp:posted format="%Y" /> (<span></span>)<ul>
			<li><txp:posted format="%b" /> (<span></span>)<ul>

	<li class="article"><txp:permlink><txp:title /></txp:permlink></li>



Roughly speaking, every time a new month/year is encountered, we close the current article list and open the next one.


But the problem of counters remains – see these empty () spans? A natural solution is to query the database for article counts for each year/month, but this would take time. And actually the articles are already retrieved – we only have to count them.

Use etc_query to replace the empty span tags

This is the very job for etc_query plugin, which does it in one line:

<txp:etc_query data='<txp:variable name="archive" />' query="li" replace=".//span={count(..//li[@class='article'])}" wraptag="ul" />

How it works? It takes the archive list, retrieves the top li elements (years), and replaces each span placeholder with the number of all li with class="article" found inside its parent. Could it be any easier?

comments powered by Disqus