Grouping search results

In the post Restrict content search to a single Collection I discussed how perch_content_search() can be used to search the content of Runway Collections and how you can display the results that come from a specific Collection.

We can use the same approach to display the results from multiple Collections in a way the results are grouped by their source Collection.

Continuing with our Movies example, if a user types “Jones” in the search box, you can display the results like so:

<h1>Search results for "Jones"</h1>

<h2>Movies</h2>

<ul>
<li>Free State of Jones</li>
</ul>

<h2>Actors</h2>

<ul>
<li>Felicity Jones</li>
</ul>

<h2>Directors</h2>

<ul>
<li>Duncan Jones</li>
</ul>

When it comes to performing the search, it is exactly like the previous post:

$search_items = perch_content_search(perch_get('q'), [
    'apps' => ['PerchContent_RunwaySearch'],
    'skip-template' => true,
    'count' => null,
]);

Now instead of checking a result item’s result_region_key against a single value of a single Collection key, we check it against multiple. Then we add the matching items to the corresponding array.

$movie_items = $actor_items = $director_items = array();
foreach($search_items as $item) {
    switch($item['result_region_key']) {
        case 'Movies':
            $movie_items[] = $item;
            break;

        case 'Actors':
            $actor_items[] = $item;
            break;

        case 'Directors':
            $director_items[] = $item;
            break;
    }
}

And lastly we can display them separately with perch_template() or perch_collection() (refer to the previous post for the explanation on the difference and when you might use one over the other).

perch_template('movies/list.html', $movie_items);
perch_template('actors/list.html', $actor_items);
perch_template('directors/list.html', $director_items);
link

Related articles