Textpattern tips, tutorials and code snippets

Edit the category tag output

I recently saw an example on the forums where someone was using a plugin to strip the lone comma from the output of the category links – if there is only one category assigned to an article. This is not necessary – Textpattern has a tag which allows you to output whatever you want.

The default way

 <p class="tags"><txp:category1 title="1" link="1" />, <txp:category2 title="1" link="1" /></p>

As a reminder of the default way of displaying the category links, the above is from the default form in a clean Textpattern CMS install. You can see the lone comma after the category1 tag.

A better way

I use something like this in my projects instead – its more flexible and allows one to strip the comma:

<txp:category1 title="1" /><txp:if_article_category number="2"> / <txp:category2 title="1" /></txp:if_article_category>

We make use here of the if_article_category tag. This tag checks if the category is assigned to an article. From TextBook:

It will execute the contained statement if the category name associated with a particular article (Category1 or Category2) matches the values of the name and number attributes. Should be used in an article form.

Actually you can place it in a misc form if you wish – it will work just fine. You’ll notice from my example above that if category2 has been assigned, then a / is displayed.

Checking if any category has been assigned

Maybe you will have situations where you may have one or two categories assigned to an article, or none at all. Then I would use the following code snippet:

<txp:if_article_category number="1"><txp:category1 link="1" title="1" /></txp:if_article_category> <txp:if_article_category number="2">, <txp:category2 link="1" title="1" /></txp:if_article_category>

Simple, and no need for a plugin!

1 Comment Comment feed

Thanks. To cover the single ‘category’ vs. two ‘categories’ in the announcement you should double the if condition. I use:

<txp:if_article_category number="2">Kategorien: <txp:else />Kategorie: </txp:if_article_category><txp:category1 link="1" title="1" /><txp:if_article_category number="2">, <txp:category2 link="1" title="1" /></txp:if_article_category>

As I am using the code everywhere I should have stored it in an extra form category_header :)

Add a comment

Use Textile help to style your comments