在functions.php中添加以上代碼
方法 一
function mt_highlight_keys( $text ) { if ( is_search() && !is_admin() ) { $s = trim( get_search_query() ); // 將字符串中的正斜杠替換為轉義正斜杠,防止造成正則表達式被終止 $s = str_replace('/', '\/', $s); $s = preg_replace( "/[\s]+/", " ", $s ); $keys = explode(' ', $s); $text = preg_replace('/(' . implode('|', $keys) . ')/iu', '<span style="color:#c00;">$1</span>', $text); } return $text; } add_filter( 'the_title', 'mt_highlight_keys' ); add_filter( 'the_excerpt', 'mt_highlight_keys' );
方法二
function search_word_replace($buffer){ if(is_search()){ $arr = explode(" ", get_search_query()); $arr = array_unique($arr); foreach($arr as $v) { if($v) { // 將字符串中的正斜杠替換為轉義正斜杠,防止造成正則表達式被終止 $v = str_replace('/', '\/', $v); $buffer = preg_replace("/(".$v.")/i", "<span style=\"color:#c00;\"><strong>$1</strong></span>", $buffer); } } } return $buffer; } add_filter("the_title", "search_word_replace", 200); add_filter("the_excerpt", "search_word_replace", 200); add_filter("the_content", "search_word_replace", 200);
注:方法二會在搜索出現空格的時候出現html標簽被解析的情況,建議使用方法一
例: