2014年08月25日 web関連WordPressphp

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();

この投稿へのコメント

コメントはまだありません。

コメントを残す

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

次のHTML タグと属性が使えます。
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CAPTCHA


ピックアップ記事

jQuery Ratyでレーティング(評価)表示

2013年10月21日 WordPressjQuery・javascriptphp
jQuery Ratyでレーティング(評価)表示
ホームページやブログの記事なんかにスター評価を表示させたい場合は、jQuery Ratyで簡単に設定出来ます。 jQuery Raty - A Star Rating Plugin ダウンロード まずは、必要なファイルを以下からダウンロードします。ダウンロードしたファイルを解凍して、jquery.raty.min.jsとimgフォルダ(星の画像)を任意の場所にアップロー…
「jQuery Ratyでレーティング(評価)表示」をはてなブックマークに追加

wordpress カスタムフィールドの値で記事一覧取得、並び替え

2020年01月10日 WordPress
カスタムフィールドの条件が一つの場合 [php]<?php $args = array( 'posts_per_page' => -1, // 全件取得 'category' => array( 12,14 ), // カテゴリ 'meta_key' => 'finished', //カスタムフィールドのキー 'meta_value'…
「wordpress カスタムフィールドの値で記事一覧取得、並び替え」をはてなブックマークに追加

Timestamp out of bounds と表示される時

2011年07月26日 web関連php
プログラムを実行しようとすると「Timestamp out of bounds」というエラーが表示されました。 何かと思って調べてみると、どうやらサーバの時間がずれている模様。 なので、以下のようにして解決。 …
「Timestamp out of bounds と表示される時」をはてなブックマークに追加

親カテゴリIDを取得・表示

2011年11月28日 WordPress
現在表示中のページ(記事)の親カテゴリIDを表示させます。 [php] <?php // 現在のカテゴリ-を配列取得 $cat_now = get_the_category(); // 親の情報を$cat_nowに格納 $cat_now = $cat_now[0]; //category_parentを$parent_idに格納 $parent_id = $cat_now->cate…
「親カテゴリIDを取得・表示」をはてなブックマークに追加
© graffiti on the web . All rights reserved. WordPress Theme by comfy