こんなので、いかが?
/**
* Google 風抜粋表示関数
*
* ループ以外の場所で使われたら、何もしない。search.php 以外では、通常の抜粋表示
* を使う。検索文字列が複数の場合は、最初に出現した文字列を中心に計算をする。
* mb_string モジュール必須。
*
* @param 表示する文字数を表す整数: デフォルト150文字
*/
function the_googlean_excerpt( $num_chars = 150 ) {
if (!in_the_loop()) return;
if (!is_search()) return the_excerpt();
mb_internal_encoding('UTF-8');
$median = $num_chars >> 1;
$search_words = get_query_var('s');
$key_words = explode(' ', $search_words);
$content = strip_tags(get_the_content());
if (($content_len = $anchor = mb_strlen($content)) > $num_chars) {
for ($i = 0, $len = count($key_words); $i < $len; $i++) {
$position = mb_stripos($content, $key_words[$i]);
if ($anchor > $position) $anchor = $position;
}
if ($anchor + $median > $content_len) $start = $content_len - $num_chars;
else if ($anchor - $median < 0) $start = 0;
else $start = $anchor - $median;
$content = mb_substr($content, $start, $num_chars);
}
$key_words = array_map(function($str) { return '/'.$str.'/i'; }, $key_words);
$content = preg_replace_callback($key_words, function($matches) {
return '<strong>' . $matches[0] . '</strong>';
}, $content);
echo $content . '...';
}
テンプレートの抜粋を表示したいところに、
the_googlean_excerpt();
と書いてくだされ。引数に文字数を指定すると、その文字で表示するはず。マークアップはお好きにどうぞ。
ありがとうございます!
理想通りになりました。素晴らしいです…!!
ちなみになんですが、タグ別アーカイブのページ(tag.php)でも同じ事をしたいのですが、上記のコードを少し修正して出来るものなのでしょうか…?
お手数ですが教えて頂けると嬉しいです。
よろしくお願い致します。