Forum

Thread tagged as: Problem, Runway

Listing only categories with assigned items (non-zero count)

Evening Perchers! I have a collection of houses, each of which is categorised by an activities / filter category (fishing, golf, etc) - Any idea how I can list only the categories that have been assigned to houses? i.e. those with a non-zero category count (for that collection?). I don't want empty categories appearing in the list as when the category link is clicked there are no houses to display.

Does this require an 'each' callback function? Any help or suggestions would be much appreciated!

my php:

        perch_categories([
            'set' => 'category-filters',
            'template' =>'category_filter_list.html',
        ]);

The category-filter-list.html template:

<perch:before><h2>Filter Houses &rsaquo;</h2>
<ul class="inline-list"></perch:before>
    <li><a href="/houses/category/<perch:category id="catSlug" type="slug" />"><perch:category id="catTitle" /></a></li>
<perch:after></ul></perch:after>
Adam Green

Adam Green 0 points

  • 4 years ago
Drew McLellan

Drew McLellan 2638 points
Perch Support

I don't think we have a way to do that currently.

Hey Adam,

I just ran into the same problem. Here's how I solved this (although it might be far from optimal):

<?php 
// get all categories into an array
$cats = perch_categories([
    'set' => 'SETSLUG',
    'skip-template' => true
]);
// walk through the array…
foreach($cats as $value) {
    // …get the items assigned to the current category into an array…
    $catCount = perch_content_custom('YOUR REGION HERE', array(
        'skip-template' => true,
        'category' => $value['catPath']
    ));
    // …and if this array contains items…
    if(count($catCount)) {
        // …output the category as needed
        print '<li>' . $value['catTitle'] . '</li>';
    }
}
?>

Hope that helps.
Best, Nils.