Close and Go BackBack to Viget

Displaying Related Categories in ExpressionEngine

Keith Muth
Keith Muth, ON THE TOPIC OF Tips and Tricks
Jun18 4

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}
Patrick said on 06/20 at 05:51 PM

Very nice blog guys! One of the most visually appealing that I’ve seen in a while. I also like the diversity of your posts. You go from the aesthetics of the site down to the coding and structure of it. Great job!

Adam said on 06/21 at 01:09 PM

I’ve struggled with that exact problem MANY times in EE - many thanks for sharing your elegant solution. It’ll come in handy on almost every project.

One minor quibble (or question): The header “Related Articles,” in my opinion, is not an item in the list. Shouldn’t it sit outside the ul tag?

Bluehost HostGator said on 06/22 at 09:39 AM

Nice idea, but do related categories useful? I think related post is more useful than categories, but thank you all the same :-)

Keith Muth said on 06/23 at 07:37 AM

Adam, good point, that H3 should really be outside of the list. I think it was in there from when we originally were working on this solution and I just never took it out. I went ahead and changed it, but thanks for the heads up!

Name:

Email:

URL:

Not a robot? Prove it by entering the word below.


Remember my personal information

Notify me of follow-up comments?