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