WordPressの抜粋表示の設定

WordPressの抜粋表示(excerpt)を以下のように動作させたかったので、自作してみました。

  1. 抜粋があれば抜粋表示
  2. moreタグがあれば、それに従う
  3. 指定文字数より本文文字数が少なければ、そのまま表示
  4. 指定文字数より本文文字数が多ければ抜粋表示

コード

functions.phpにコピペ。

<?php
//WordPress抜粋表示の変更
/****
1.抜粋があれば抜粋表示
2.moreタグがあれば、それに従う
3.$lengthより文字が少なければ、そのまま表示
4.$lengthより文字が多ければ抜粋表示
****/
function set_excerpt( $length=200 ){
	global $post;
	//抜粋が入力されていれば、抜粋表示($length無効)
	if(has_excerpt()) {
		$content = strip_tags(get_the_excerpt());
		$content = $content . '…'.'<div class="more"><a href="'.get_permalink().'" class="btn btn-default btn-md"><span class="glyphicon glyphicon-ok"></span> この記事の続きを読む</a></div>';
	//moreタグがある場合
	//}elseif(preg_match('/<!--more(.*?)?-->/u', $post->post_content, $matches)){
	}elseif(strpos($post->post_content,'<!--more')){
		global $more; $more = 0;
		$content = strip_tags(get_the_content(''));
		$content = $content . '…'.'<div class="more"><a href="'.get_permalink().'" class="btn btn-default btn-md"><span class="glyphicon glyphicon-ok"></span> この記事の続きを読む</a></div>';
	//本文の文字数が$lengthより少ない場合は全文表示
	}elseif(mb_strlen( $post -> post_content) <= $length){
			$content = strip_tags(get_the_content());
	}else{
		 $content = mb_substr( strip_tags( $post -> post_content ), 0, $length );
		 $content = $content . '…'.'<div class="more"><a href="'.get_permalink().'" class="btn btn-default btn-md"><span class="glyphicon glyphicon-ok"></span> この記事の続きを読む</a></div>';
	}	
		 return $content;
}

?>

使用方法

テーマファイルの本文の抜粋を表示させたいにset_excerpt();

コメントする

メールアドレスが公開されることはありません。

CAPTCHA