Displaying Related Categories in ExpressionEngine

While working with ExpressionEngine on a client project, Doug Avery and I ran across a problem. We had a weblog full of articles, and we wanted to show a list of related articles on single entry pages. The key was using EE's related_categories_mode parameter, which pulls back entries based on categories in the entry.

The problem was that you can't nest weblog tags...so, the related categories tag had to sit outside of the articles weblog entries, and we needed a way to tell EE to only display the related articles at the bottom of full article pages.

This is easy enough if you just want to output them as standalone tags (for example, a group of repeating links), but gets tricky if you want to add a header, or place them as LIs inside a UL. Any markup outside the related_categories_mode weblog tag remains even if no articles are returned, meaning empty UL's and headers were showing up beneath every entry on the blog's index page.

We knew we wanted the UL and H3 to appear inside the tag, but in EE, everything inside a weblog tag repeats with each entry. With the H3 placed inside the tag, our full article pages were showing one header and one UL for each link which looks totally ridiculous.

The solution (which I largely credit to Doug) is to use a few simple IF statements to figure out when an article is the first/last in a list, and add then the necessary markup:

 {exp:weblog:entries related_categories_mode="on"} {if count == "1"} <h3>Related Articles</h3> <ul class="relatedArticles"> {/if} <li> <a href="{title_permalink="articles/"}">{title}</a> </li> {if count == total_results} </ul> {/if} {/exp:weblog:entries} 
Keith Muth

,
Posted in Article Category: #Design & Content
on