get_the_excerpt()


WordPressのget_the_excerpt()関数は、投稿や固定ページの抜粋を取得するために使用されます。抜粋が明示的に設定されていない場合、自動的に生成されます。

構文

get_the_excerpt( int|WP_Post $post = null );
  • $post(int|WP_Post) — 抜粋を取得する投稿のIDまたはWP_Postオブジェクト。デフォルトは現在の投稿。

例1: 抜粋を表示する

基本的な例で、投稿の抜粋を表示します。

<?php echo get_the_excerpt(); ?>

例2: 特定の投稿の抜粋を取得する

指定した投稿IDの抜粋を取得します。

<?php echo get_the_excerpt(get_post(123)); ?>

例3: 抜粋の長さを変更する

抜粋の長さを変更するために、excerpt_lengthフィルタを使用します。

add_filter('excerpt_length', function($length) { return 20; }); echo get_the_excerpt();

例4: 抜粋の末尾のテキストを変更する

抜粋の末尾に表示されるテキストを変更するために、excerpt_moreフィルタを使用します。

add_filter('excerpt_more', function($more) { return '...続きを読む'; }); echo get_the_excerpt();

例5: カスタム投稿タイプの抜粋を取得する

カスタム投稿タイプの抜粋を取得します。

<?php $args = array('post_type' => 'custom_post_type', 'posts_per_page' => 1); $query = new WP_Query($args); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); echo get_the_excerpt(); } } wp_reset_postdata(); ?>

例6: 抜粋を変数に格納する

抜粋を変数に格納して後で使用します。

<?php $excerpt = get_the_excerpt(); echo $excerpt; ?>

例7: 抜粋が空の場合のデフォルトテキストを設定する

抜粋が空の場合にデフォルトのテキストを表示します。

<?php $excerpt = get_the_excerpt(); if (empty($excerpt)) { echo 'この投稿には抜粋がありません。'; } else { echo $excerpt; } ?>

例8: 抜粋をHTMLタグ付きで表示する

抜粋をHTMLタグ付きで表示します。

<?php echo wpautop(get_the_excerpt()); ?>

注意点

  • 抜粋が明示的に設定されていない場合、自動生成される抜粋は本文の最初の55語から生成されます。
  • HTMLタグは抜粋から削除されますが、wpautop()関数を使用することで段落タグを追加できます。

関連機能: