Hello everyone. I want to highlight keys in the title of search results.

I tried this:

variable_set('apachesolr_hl_fieldtohighlight', 'title,body');
variable_set('apachesolr_hl_active', 'on');
variable_set('apachesolr_hl_textsnippetlength', 200);
variable_set('apachesolr_hl_pretag', '<span>');
variable_set('apachesolr_hl_posttag', '</span>');
variable_set('apachesolr_hl_numsnippets', 1);

but it doesn't work.

For now I'm doing it this way:

function hook_theme_search_api_page_results(array $variables) {
...
  $items = $variables['items'];
  $keys = $variables['keys'];
...
  $ks = explode(' ', $keys);
  foreach ($ks as $k) {
    $item->title = preg_replace("/$k/i", '||' . $k . '|||', $item->title);
  }
...
}

And later in *search-index.tpl.php files

print str_replace(array('|||', '||'), array('</strong>', '<strong>'), $title)

But I believe that it's an awful hack. So can I do it properly?

CommentFileSizeAuthor
#4 title-highlighted.png17.04 KBsoulfroys

Comments

pwolanin’s picture

In the D7 schema, the fields are label and content, maybe try using those names?

Also, the way snippets are handled probably won't give you what you want.

nick_vh’s picture

Status: Active » Postponed (maintainer needs more info)

can we close this Soul88?

soul88’s picture

Status: Postponed (maintainer needs more info) » Closed (fixed)

Sure, sorry for delaying the process. Let it be closed.

Unfortunately I don't know whether this solution fixes the problem, cause we already deployed the project and I don't have a working copy of it near me.

So, hopefully will have a chance to check it during the next one.

Thanks again for your help!

soulfroys’s picture

StatusFileSize
new17.04 KB

I needed this for a D6 project. I did the following:

1 - Hack (arg!) the apachesolr_search.module file:

- 'hl.fl' => ’content',
+ 'hl.fl' => array('content', 'label'),

2 - Put search-result.tpl.php and search-results.tpl.php in your template folder.

3 - Change the output in search-result.tpl.php:
<a href="<?php print $url; ?>"><?php print (isset($result['snippets']['label'])) ? filter_xss($result['snippets']['label']) : $title; ?></a>

Is there a cleaner/better way to do this?

soulfroys’s picture

The proper way without hacking:

1 - Use hook_apachesolr_query_alter:

function [mymodule]_apachesolr_query_alter($query) {
  // Highlight the label field
  $query->addParam('hl.fl', 'label');
}

2 - Use preprocess function to clean up the output:

function [template]_preprocess_search_result(&$variables) {
  // Highlighted title 
  $variables['title'] = filter_xss($variables['result']['snippets']['label']);
}

3 - Put search-result.tpl.php and search-results.tpl.php in your template folder. No need to change anything:

<a href="<?php print $url; ?>"><?php print $title; ?></a>

[EDITED]
Sorry, typo correction...