ホーム >  WordPress >  本文抜粋を取得する方法

投稿日:   |  最終更新日:

本文抜粋を取得する方法

WordPress

WordPressのサイトを作ったとき、本文の内容をすこし紹介したいときがあります。このとき、本文を一部抜粋しますので、「get_the_excerpt()」という関数を使用します。

wp0003

しかし、この関数はショートコードや特殊文字も含まれてしまいます。メインループ内で使用すると動作が変わり、非常に使いづらいものです。

そこで、「get_the_excerpt()」で取得した本文から以下の内容を削除します。

  • moreタグ以降の内容
  • ショートコード
  • htmlタグ
  • 特殊文字削除

コード


function get_the_replace_excerpt($content, $length) {
  $length = ($length ? $length : 70);
  $content =  preg_replace('/<!--more-->.+/is',"",$content); 
  $content =  strip_shortcodes($content);
  $content =  strip_tags($content);
  $content =  str_replace("&nbsp;","",$content);
  $content =  mb_substr($content,0,$length);

  return $content;
}

使用例

$wp_query = new WP_Query($args);
if($wp_query->have_posts()):
    while ( $wp_query->have_posts() ) : 
        $wp_query->the_post();
?>
    <p><?php echo get_the_replace_excerpt($post-> post_content ,100) ; ?></p>
<?php
    endwhile;
endif;

解説

関数「get_the_replace_excerpt」を、functions.phpにコピペし、テーマのテンプレート内で使用します。

引数は、「$content」と「$length」です。

「$content」は、本文全体を渡します。呼び出し側(index.php)は、「get_the_content()」あるいは「$post->post_content」を記述します。

$lengthは、文字列の長さを指定します。

トラックバック用のURL
プロフィール

名前:イワサキ ユウタ 職業:システムエンジニア、ウェブマスター、フロントエンドエンジニア 誕生:1986年生まれ 出身:静岡県 特技:ウッドベース 略歴 20

最近の投稿
人気記事
カテゴリー
広告