2011-12-19 60 views
1

我正在玩标准WordPress的搜索,并在功能文件中使用此代码来突出显示的结果内容中搜索到的术语。Wordpress,修剪跨度标签周围显示的内容

function search_content_highlight() {$content = get_the_content(); 
$keys = implode('|', explode(' ', get_search_query())); 
$content = preg_replace 
('/(' . $keys .')/iu', '<strong class="search- highlight">\0</strong>', $content); 
echo '<p>' . $content . '</p>'; 
} 

现在用的是内容,而不是摘录所以它总是实际显示所需要的字,但编号真的爱修剪的内容,所以它只是一个十几词搜索词的两侧,这是在上面的代码中的强标签中。对于所有这些我都很新颖,但是我希望有人能够指出我的方向是否正确。

在此先感谢您的帮助!

回答

0

我猜你会想显示所有粗体字的最小值。要做到这一点,您需要找到您找到匹配单词的第一个和最后一个实例的位置。

function search_content_highlight() 
{ 
    $content = get_the_content(); 
    $keysArray = explode(' ', get_search_query()); 
    $keys = implode('|', $keysArray); 
    $content = preg_replace('/(' . $keys .')/iu', '<strong class="search-highlight">\0</strong>', $content); 
    $minLength = 150; //Number of Characters you want to display minimum 
    $start = -1; 
    $end = -1; 
    foreach($keysArray as $term) 
    { 
     $pos = strpos($content, $term); 
     if(!($pos === false)) 
     { 
      if($start == -1 || $pos<$start) 
       $start = $pos-33; //To take into account the <strong class="search-highlight"> 
      if($end == -1 || $pos+strlen($term)>$end) 
       $end = $pos+strlen($term)+9; //To take into account the full string and the </strong> 
     } 
    } 
    if(strlen($content) < $minLength) 
    { 
     $start = 0; 
     $end = strlen($content); 
    } 
    if($start == -1 && $end == -1) 
    { 
     $start =0; 
     $end = $minLength; 
    } 
    else if($start != -1 && $end == -1) 
    { 
     $start = ($start+$minLength <= strlen($content))?$start:strlen($content)-$minLength; 
     $end = $start + $minLength; 
    } 
    else if($start == -1 && $end !=-1) 
    { 
     $end = ($end-$minLength >= 0)?$end:$minLength; 
     $start = $end-$minLength; 
    } 
    echo "<p>".(($start !=0)?'...':'').substr($content,$start,$end-$start).(($end !=strlen($content))?'...':'')."</p>"; 
}  

我测试了上面的代码,它的工作原理。你可能要考虑添加更多的逻辑来获得最大描述尺寸

+0

感谢你们,使用你的代码Josh并且它工作的很好。感谢那!! – 2011-12-19 22:27:20

0

为什么不使用插件?

WordPress Highlight Search Terms

另外,如果你正在寻找截断$content变量,试试这个功能:

function limit_text($text, $limit) { 
    if (strlen($text) > $limit) { 
     $words = str_word_count($text, 2); 
     $pos = array_keys($words); 
     $text = substr($text, 0, $pos[$limit]) . '...'; 
    } 

    return $text; 
} 

from here