[WordPress] 検索結果検索文字ハイライトする方法

1 min read
hiroweb developer

検索結果に表示された文字列をハイライト表示させる。

コード

function highlight_search_results($content) {
    if (!is_admin() && is_search() && is_main_query()) {
        $keys = implode('|', explode(' ', get_search_query()));
        $content = preg_replace('/'. $keys .'/iu', '<mark>$0</mark>', $content);
    }

    return $content;
}

add_filter('the_title', 'highlight_search_results');
add_filter('the_excerpt', 'highlight_search_results');

the_title(記事タイトル)、the_excerpt(記事内容)、the_excerpt(記事抜粋)などにもadd_filterでハイライトを付与する事が可能だが、記事抜粋など$content内に検索文字列がないとハイライトできない。