wordpress搜索結果中的關鍵詞高亮


在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標簽被解析的情況,建議使用方法一

例:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM