2016-12-29 45 views
1

我使用WordPress的木材插件。樹枝突出顯示詞(木材插件)

我創建了一個結果搜索頁面。我想突出顯示用戶搜索的字詞。

在PHP中我寫道:

$highlight = array(); 
if ($terms) { 
    foreach($terms as $term) { 
     array_push($highlight, '<span class="blue bold">'.$term.'</span>'); 
    } 
} 

而這,更換搜索詞中的PHP:

<p class="date red"><?php echo str_ireplace($terms, $highlight, get_field('subtitle_post')); ?></p 

但我不知道如何變換,在嫩枝(木材) ?

回答

1

您應該使用自定義的樹枝過濾器。

從文檔:extending timber。 (我試過,以使其適應你的榜樣,但你可能需要改變它)

/* functions.php */ 

add_filter('get_twig', 'add_to_twig'); 

function add_to_twig($twig) { 
    /* this is where you can add your own fuctions to twig */ 
    $twig->addExtension(new Twig_Extension_StringLoader()); 
    $twig->addFilter(new Twig_SimpleFilter('highlight', 'highlight')); 
    return $twig; 
} 

function highlight($text, array $terms) { 

    $highlight = array(); 
    foreach($terms as $term) { 
     $highlight[]= '<span class="blue bold">'.$term.'</span>'; 
    } 

    return str_ireplace($terms, $highlight, $text); 
} 

那麼你可以使用自定義過濾,

{{ yourField|highlight(words) }}