Creating sub navigation with the category archive tag

A difficult concept to understand when starting to develop with ExpressionEngine is URL structure, and how this impacts the different modules. I wanted to set up a simple sub navigation mechanism where individual entries are listed under their category. I didn’t want all entries listed for each category, I only wanted to display the entries for the category currently being viewed. Kind of like this:

sub category navigation

That seemed like a very basic thing to do. I thought the category or category_archive modules would work the best. I couldn’t find a way to configure those tags to list all categories, but only list entries under the current category. I thought that PHP might solve the problem.

I started down the route of creating some PHP to grab the URL segment, convert it to lower case, compare it to the category name, and echo out the appropriate HTML. It worked, sort of. Even though I could get the HTML to come out correctly, the URLs for each entry were not working. And this was relying on the fact that all my categories were one word. I would have to add additional PHP to account for multiple word categories.

There is a much simpler way to do this, without resorting to PHP. EE has built in conditionals which function the same way as in other programming or scripting languages. If you are already familiar with JavaScript, PHP, or ActionScript, the conditionals will be a piece of cake. See the documentation.

The other tag I was not aware of is the category_url_title, which is basically what I was creating with PHP, using the category_name. You can easily compare the category_url_title with the URL segment using conditionals, and return specific code if the two are equal.

To create sub navigation under the current category, you can use the weblog entries tag. I needed to create a custom URL for each entry, which seems kind of like a hack, but it works. The only remaining issue is that once you select an entry and go to the details page, the category sub navigation is lost since the category is no longer in the URL. I’m sure there’s a way to correct it, but I’m setting the idea aside for now.

Code:


<ul>
{exp:weblog:category_archive weblog="projects" style="linear" show_empty="no"}
{categories}
{if segment_4 == category_url_title}
<li class="open"><a href="{path="projects/list"}"><em>{category_name}</em></a>
  <ul>
    {exp:weblog:entries weblog="projects" disable="categories|member_data|pagination|trackbacks"}
    <li><a href="{site_url}index.php/projects/details/{url_title}">{title}</a></li>
    {/exp:weblog:entries}
  </ul>
</li>
{if:else}
<li><a href="{path="projects/list"}">{category_name}</a></li>
{/if}
{/categories}
{/exp:weblog:category_archive}
</ul>

Leave a Reply

Your email address will not be published.

%d bloggers like this: