Filter multiple categories

I’m working on a filtering system for a portfolio website but have come into a bit of trouble. The filter itself works but the trouble comes in now that I have multiple categories per project. For example some projects have “editorial” and “exhibition” as categories. Unfortunately if the projects have more than one category they don’t show up in the filtered list.

Here is the blueprint for the project pages

title: Project

sections:
  info: 
    type: fields
    fields:
      Title:
        type: text
      Category: 
        type: checkboxes
        options:
          Exhibition: Exhibition
          Editorial: Editorial
          Identity: Identity
          Product: Product
          Web: Web
        save: queryCategories

      Info:
        type: textarea
        markdown: true

  gallery:
    type: files
    layout: cards 
    image:
      ratio: 1/1

This is the php filter loop

<?php
        $page = page('projects');
        $filterBy = get('filter');
        $unfiltered = $page->children();
        $projects = $unfiltered
            ->when($filterBy, function ($filterBy) {
                return $this->filterBy('category', $filterBy);
            });
        $filters = $unfiltered->pluck('category', ',', true);

        // Create an array to map project IDs to their slide indices
        $projectMap = [];
        $index = 0;
        foreach ($projects as $project) {
            $projectMap[$project->id()] = $index;
            $index++;
        }
        ?>

And this is where the projects are being pulled in

<div class="indexRight">
                <ul>
                    <?php foreach ($projects as $project) : ?>
                        <li data-index="<?= $projectMap[$project->id()] ?>" class="listHover">
                            <a class="itemLeft" href="<?= $project->url() ?>"><?= $project->title() ?></a>
                            <a class="itemRight" href="<?= $project->url() ?>"><?= $project->category() ?></a>
                        </li>
                    <?php endforeach ?>
                    <!-- Show the "Back" option only when the filter is active -->
                    <?php if ($filterBy) : ?>
                        <li>
                            <a href="<?= $page->url() ?>" class="filterReturn">Back</a>
                        </li>
                    <?php endif ?>
                </ul>
            </div>

According to this cookbook: filtering compendium the problem might be in your use of filterBy(). Maybe try filter() instead…?

Thanks but that didn’t seem to help sadly

Hi, I actually found an older post that helped me solve it. Just needed to make this change

return $this->filterBy('category', $filterBy, ',');

1 Like