Close and Go BackBack to Viget

Displaying Related Categories in ExpressionEngine

Keith Muth
Keith Muth, ON THE TOPIC OF ExpressionEngine and Tips and Tricks
6/18
2008

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}
blog comments powered by Disqus

We're The Designers

at Viget Labs. We write about design news, trends, techniques, buildout, inspiration, CSS, and our projects.

What's a-twitter?

Follow us @VigetInspire for updates of the goings-on here or @Viget for more from all of the Viget crew. #thatisall

Contact Us

Have any questions, comments, ideas, or secrets to share? Let us know.


What color is the sky?

Sorry, you need to have Javascript enabled to use this form. (Don't blame us, blame the spammers!) If you'd like to contact us, please visit our Contact page.