Search also in structure field

HI,
I would like to display the search result width the highlightet result item like @larshaendler proposed.

e.g.

$char_before = 10;
$char_after = 40;
$result_wrap_left = '<mark>';
$result_wrap_right = '</mark>';
$outer_wrap = '...';
$target = 
$text = strip_tags($result->text()->kirbytext()->html());

$pos = stripos($text, esc($query));

$output = $outer_wrap;
$output.= substr($text, $pos-$char_before, $char_before);
$output.= $result_wrap_left;
$output.= substr($text, $pos, strlen(esc($query)));
$output.= $result_wrap_right;
$output.= substr($text, $pos+strlen(esc($query)), $char_after);
$output.= $outer_wrap;

print($output);

…t unserer Kunden erhalten. Fairness und Loyaliät Wir s…

… die sich Kunden anpasst. Die operative Nähe zu Ihnen …

…gen Ihrer Kunden immer gerecht werden. Die Bereitschaft …

The problem is, that the output is always the textfield because I am asking for $result->text()?

Is there a way to find out in wich field the $query appears?

1 Like

I have made a widget that searches over all blog articles and there structure field (comments). Maybe my widget filter can help you:

<?php
return array(
  'title' => 'Unmoderated comments',
  'html' => function() {
    return tpl::load(__DIR__ . DS . 'moderate.html.php', array(
      'posts' => panel()->site()->page('blog')->children()->visible()->filter(function($p) {
        return $p->comments()->toStructure()->filterBy('moderated', '==', 'false')->count() > 0;
      })
    ));
  }
);
2 Likes

AFAIK, there is no way to get the field from the query. One way of achieving what you want would be to go through each relevant field to check if the query expression is contained in it:

<?php
$query = 'something';
$results = $site->search($query);

foreach($results as $result):

  if(stripos($result->text()->value(), $query)) {
    $text = strip_tags($result->text()->kirbytext()->html());
  } 
  if(stripos($result->intro()->value(), $query)) {
    $text = strip_tags($result->intro()->kirbytext()->html());
  }

For structure fields, this is a bit more complicated, though.

2 Likes

Thank you, both of you,
@Svnt to fetch all was not the problem but out put the correct part of the text.

I did it now like this:

<?php foreach($results as $result):

if(stripos($result->text()->value(), $query)) {
  $text = strip_tags($result->text()->kirbytext()->html());
} 
if(stripos($result->abstract()->value(), $query)) {
  $text = strip_tags($result->abstract()->text()->kirbytext()->html());
} 
if(stripos($result->accordion()->text()->value(), $query)) {
  $text = strip_tags($result->accordion()->text()->kirbytext()->html());
} ?>

Thanks a lot!

1 Like