コンテンツ(投稿記事/固定ページ)の抜粋を出力/取得

コンテンツ(投稿記事/固定ページ)の抜粋を出力または取得するには、the_excerpt関数またはget_the_excerpt関数を使用します。
the_excerpt関数はechoで出力するのに対して、get_the_excerpt関数はreturnで返します

抜粋が設定されていない場合は本文を文字数を制限(初期は110文字)して返します。
また、末尾に省略文字(初期は" […]")が付きます。
制限については 本文の文字数の制限をご覧ください。

  • ※ サブループ内でのみ取得可能です。
  • ※ the_excerpt関数は改行等HTMLへ変換されます。
  • ※ 抜粋が設定されていない場合の本文はHTMLが除かれた状態で返します。

構文

出力

the_excerpt();

取得

戻り値 = get_the_excerpt();

戻り値

取得した抜粋を返します。

サンプルコード

$excerpt = get_the_excerpt();

本文の文字数の制限

the_excerpt関数で抜粋が設定されていない場合に返す本文の制限される文字数は初期で110文字です。
制限する文字数を変更したい場合は、functions.phpファイルに次のコードを追加します。

if (!function_exists('custom_excerpt_length')) {
    function custom_excerpt_length($length) {
        return 50;
    }
}
 
add_filter('excerpt_length', 'custom_excerpt_length');

returnで制限する文字数を返します。

省略文字

省略文字は初期で […]が表示されます。
省略文字を変更したい場合は、functions.phpファイルに次のコードを追加します。

if (!function_exists('custom_excerpt_more')) {
    function custom_excerpt_more($more) {
        return '...';
    }
}
add_filter('excerpt_more', 'custom_excerpt_more');

returnで表示する文字を返します。

CMS「WordPress」逆引きリファレンス一覧へ戻る