Is there a way to include content in structure fields into search results?
Content within a structure field is automatically searched if you search through pages.
What is your use case? Do you want to specifically search through structure fields and return a specific result?
Well, it is strange, it doesn’t show up.
I use the standard controller
<?php
return function ($site) {
$query = get('q');
$results = $site->search($query, 'title|text');
return [
'query' => $query,
'results' => $results,
];
};
So I search the whole site, right?
Well, not exactly, you limit your search to the title and text fields, and I have my doubts that that includes your structure fields.
So how do I include structure fields? Can I include all structure fields or must I specify which ones? But then I would have to update my controller if I add a structure field in the future.
If you don’t specify any fields, Kirby will search in all fields. That would be one option. You could also check if a page has structure fields and include those.
Example code:
// get all fields from the blueprint
$fields = $page->blueprint()->fields();
//filter fields by type structure
$structureFields = array_filter($fields, function($item) {
return $item['type'] === 'structure';
});
// set your standard search fields
$searchFields = 'title|text';
// check if there are any structure fields in your array and add them if
if (empty($structureFields) === false) {
$searchFields = $searchFields . '|' . implode('|', array_keys($structureFields));
}
$query = get('q');
$results = $site->search($query, $searchFields);
$results = $site->search($query);
I did it like this, but that doesn’t change the result.
Hm, should work though. I have only tested this with simple structure fields, not with nested ones (but shouldn’t make any difference).
Does the search work if you use the same text you are searching for in another (normal) field? Does the search term contain special characters?
It does. Like now. Maybe I had some strange cache issue with Firefox or Codekit didn’t work.
Please pardon the confusion and thank you agian!
No problemo!
Too bad that I can only reply with at least 20 characters, otherwise I would have just said: