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标签被解析的情况,建议使用方法一

例:

 

posted @ 2020-03-18 17:20  venkim  阅读(849)  评论(0编辑  收藏  举报