2011-12-19 57 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