Category list of articles without a plugin

This is a short and sweet little tip for those of you who need to display a list of categories along with a number of articles associated with the category.

Although there is already perfectly good TXP Tip for this, it requires a plugin. This version does not.

Create the necessary PHP code

<txp:php>
global $cat_totals;
$rs2 = safe_rows_start('Category1, count(*) as num', 'textpattern', "Section='plugins' group by Category1");
while ($a = nextRow($rs2)) {
	$cat_totals[$a['Category1']] = $a['num'];
}

$rs2 = safe_rows_start('Category2, count(*) as num', 'textpattern', "Section='plugins' group by Category2");
while ($a = nextRow($rs2)) {
	$name = $a['Category2'];
	$num = $a['num'];

	if (isset($cat_totals[$name]))	{
		$cat_totals[$name] += $num;
	} else {
		$cat_totals[$name] = $num;
	}
}
</txp:php>

For the above code, change your section name as per your needs.

First version

<txp:category_list wraptag="ul" break="li" class="directory">
<txp:category title="1" link="1" /> [<txp:php>global $cat_totals; echo $cat_totals[category(array())];</txp:php>]
</txp:category_list>

The above first version was nice except that the desired output was not quite right:

<a href="http://yoururl.com/plugins/?c=admin">Admin</a> [77]

As you can see the article count is outside the anchor tag which makes it more difficult to style.

Second version

<txp:category_list wraptag="ul" break="li" class="directory">
<a href="<txp:category link="1" />"><txp:category title="1" /> [<txp:php>global $cat_totals; echo $cat_totals[category(array())];</txp:php>]</a>
</txp:category_list>

Much better, now we have constructed the anchor tag manually we have a much better output:

<a href="http://yoururl.com/category/admin-extension">Admin extension [55]</a>

Its also nicer in that we get category/admin-extension instead of ?c=admin-extension.

Final version

<txp:category_list wraptag="ul" break="" class="directory">
<li<txp:if_category name='<txp:category />'> class="active"</txp:if_category>>
<a href="<txp:site_url />category/<txp:category />"><txp:category title="1" /> [<txp:php>global $cat_totals; echo $cat_totals[category(array())];</txp:php>]</a>
</li>
</txp:category_list>

This last version sets an class="active" to the <li> tag.

Credit to Stef Dawson for the PHP code – its all his. Thanks Stef!

comments powered by Disqus