Skip to content

Instantly share code, notes, and snippets.

@gpbeer
Last active August 28, 2018 09:56
Show Gist options
  • Save gpbeer/2f05f0918fa65caeefe9ae55c28649d3 to your computer and use it in GitHub Desktop.
Save gpbeer/2f05f0918fa65caeefe9ae55c28649d3 to your computer and use it in GitHub Desktop.
Twig extension to highlight words common used for wordpress search page
<?php
namespace Theme\Twig;
class HighLight extends \Twig_Extension
{
public function getFilters()
{
return [
new \Twig_SimpleFilter('highlight', [$this, 'highlight']),
];
}
public function highlight($text, $search_query)
{
if (isset($search_query) && (!empty($search_query) && !is_null($search_query))) {
$keys = explode(" ",$search_query);
$keys = array_filter($keys);
$text = preg_replace('/('.implode('|', $keys) .')/iu', '<mark>'.$search_query.'</mark>', $text);
}
return $text;
}
}
// {{ post.title|highlight(search_query) }}
<?php
namespace Theme;
use Timber\Site;
final class ThemeSite extends Site
{
public function __construct()
{
parent::__construct();
add_filter('get_twig', [$this, 'add_to_twig']);
}
function add_to_twig($twig)
{
$twig->addExtension(new Twig\HighLight());
return $twig;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment