WordPress で構築したサイトで、ユーザーが検索機能を利用した際に、検索結果の一覧ページに表示されている記事のタイトルや本文の中から、検索されたキーワードをハイライトして表示させる方法を紹介します。 テーマファイルの[functions.php]内に以下のコードを記述するだけなので非常に簡単です。 function wps_highlight_results($text) { if(is_search()){ $sr = get_query_var('s'); $keys = explode(" ",$sr); $text = preg_replace('/('.implode('|', $keys) .')/iu', '<span class="search-highlight">'.$sr.'</span>', $text); } return $text; } add_filt
![【WordPress】ユーザーが検索したキーワードをハイライトして表示させる。](https://cdn-ak-scissors.b.st-hatena.com/image/square/31e82f23c379aaefea854c829e99a1e5283addd4/height=288;version=1;width=512/https%3A%2F%2Fon-ze.com%2Fwordpress%2Fwp-content%2Fthemes%2Fonze-2022%2Finc%2Fthumbnail%2F600x360x80-d62a012a312a06e1e5ff177bed84971b-wordpress-logo.png)