the_excerpt()


WordPressのthe_excerpt()関数は、投稿の抜粋を表示するために使用されます。この関数は、投稿の内容から自動的に抜粋を生成し、テンプレート内で簡単に表示することができます。

構文

the_excerpt();
  • the_excerpt()は引数を取りません。

例1: 基本的な抜粋の表示

この例では、投稿の抜粋を表示します。

<?php the_excerpt(); ?>

例2: カスタム抜粋の表示

カスタムフィールドを使用して抜粋を表示する例です。

<?php echo get_post_meta(get_the_ID(), 'custom_excerpt', true); ?>

例3: 抜粋の長さを変更

excerpt_lengthフィルターを使用して、抜粋の長さを変更します。

<?php add_filter('excerpt_length', function($length) { return 20; }); the_excerpt(); ?>

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

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

<?php add_filter('excerpt_more', function($more) { return '...続きを読む'; }); the_excerpt(); ?>

例5: カスタム投稿タイプでの抜粋表示

カスタム投稿タイプで抜粋を表示する例です。

<?php $args = array('post_type' => 'custom_post_type', 'posts_per_page' => 1); $query = new WP_Query($args); while ($query->have_posts()) : $query->the_post(); the_excerpt(); endwhile; wp_reset_postdata(); ?>

例6: 抜粋をHTMLタグ付きで表示

wp_trim_excerptフィルターを使用して、抜粋にHTMLタグを保持させます。

<?php add_filter('wp_trim_excerpt', function($text) { return $text; }); the_excerpt(); ?>

注意点

  • the_excerpt()は、投稿に手動で設定された抜粋がない場合、自動的に内容から抜粋を生成します。
  • 自動生成される抜粋は、HTMLタグを除去します。HTMLタグを保持したい場合は、カスタムフィルターを使用する必要があります。
  • 抜粋の長さや末尾のテキストは、フィルターを使用してカスタマイズできます。

関連機能: