Search code examples
categoriesexpressionengine

Expression Engine - For entrys listing, only show last category in tree?


I have a category structure like this:

cat1
cat2
-catA
-catB
cat3

For a list of entries Im showing the category names for each one with this: {categories show_group=“1”}{category_name}{/categories}

How can I limit the category names to only show the last in the tree when there is more than one? EG if an entry is part of ‘cat2’ and also ‘catA’, I only want ‘catA’ to display.

Thanks

Update - Ive tried the following but total_results returns the number of entries, not the number of categories for each entry.

{exp:channel:entries channel="news|blog" category="<?php echo $cat_id ?>" orderby="date" sort="desc" disable="member_data|pagination" dynamic="no"}
    {categories show_group="1"}{if count == total_results}{category_name}{/if}{/categories}     
{/exp:channel:entries}

Solution

  • The efficient way would be to write a SQL query to get exactly the value you want. The inefficient but easy way would be to hide all results except the last one.

    {!-- requires PHP parsed on output --}
    <?php $lastCat = ""; ?>
    {categories}
        <?php $lastCat = "{category_name}"; ?>
    {/categories}
    <?php echo $lastCat; ?>
    

    It turns out {count} and {total_results} aren't supported within the {categories} tag pair. You can use PHP to substitute.

    Whether inefficient is good enough depends on how many categories you have and how effective caching the page will be.