wordpress首頁中每篇文章都是全文輸出的, 不符合國人的習慣,這裏講述一個比較好的實現摘要的方法,優點:
1 適用於所有文章, 不用在文章中插入特殊的符號
2 保持文章的原有格式
以inove主題爲例修改,其他主題修改相同的文件即可
在inove/functions.php 最後的
<?php
}
?>
修改爲
<?php
}
if (! function_exists('character_limiter'))
{
function character_limiter($str, $n = 300, $end_char = '……')
{
if (strlen($str) <= $n)
{
return $str;
}
$str = preg_replace("/\s+/", ' ', preg_replace("/(\r\n|\r|\n)/", " ", $str));
if (strlen($str) <= $n)
{
return $str;
}
$out = "";
foreach (explode(' ', trim($str)) as $val)
{
$out .= $val.' ';
if (strlen($out) >= $n)
{
return trim($out).$end_char;
}
}
}
}
?>
inove/index.php 中
<?php the_content(__('Read more...', 'inove')); ?>
替換爲
<?php print character_limiter($post->post_content,1200); ?> <p> </p>
<p><a href="<?php the_permalink() ?>"><strong>繼續閱讀全文>></strong></a></p>
這個1200可以自己定義,想把摘要顯示多一些就增大。
如果你使用了google-syntax-highlighter 插件, 會出現“繼續閱讀全文” 出現在代碼段裏面的問題, 如圖
下面一片文章挺好的,但是上面的那一片文章就出現了錯亂的問題。
在上面functions.php中修改的代碼中
$out .= $val.' ';
前面加上一句,
if (strpos($val, '<pre') === 0){
return trim($out).$end_char;
}
就是發現瞭如果<pre 提前返回。
前提是你的代碼都是圈在 <pre name="code" class="java"></pre>這樣的標記中的