記事の抜粋分を取得します。抜粋の長さはデフォルトで110文字(日本語)です。
get_the_excerpt($post);| 引数 | 必須/任意 | 引数に指定するもの |
|---|---|---|
| 第1引数 $post | 任意 | 判定したい記事のID (整数)/ オブジェクト初期値: null(結果的に現在の記事の抜粋文を取得) |
戻り値(返す値):記事の抜粋文
※表示するにはechoします。
引数を指定しない場合、現在の記事の抜粋文を取得します。
get_the_excerpt();下記の例ではIDが20の記事の抜粋文を取得します。
get_the_excerpt(20);似ているテンプレートタグにthe_excerpt()があり、こちらは抜粋文を表示してくれますが自動的にpタグが生成されます。pタグなしあるいは特定のclassがついたpタグの中に抜粋文を埋め込みたいときは下記のようget_the_excerpt()を活用することができます。
<p class="excerpt">
<?php echo get_the_excerpt(); ?>
</p>home.phpやarchive.phpのような記事一覧表示用のPHPファイルに下記のようにコードを書いて、抜粋文付きの一覧を表示することができます。
<ul class="cards">
<?php while (have_posts()): ?>
<?php the_post(); ?>
<li class="cards__item card">
<a class="card__link" href="<?php the_permalink(); ?>">
<div class="card__data">
<div class="card__img">
<?php if (has_post_thumbnail()) : ?>
<?php the_post_thumbnail(); ?>
<?php else: ?>
<img src="<?php echo esc_url(get_theme_file_uri('/img/noimage.jpg')); ?>" alt="">
<?php endif; ?>
</div>
<div class="card__date"><?php echo get_the_date('') ?></div>
<div class="card__title"><?php the_title(); ?></div>
<p class="card__excerpt"><?php echo get_the_excerpt(); ?></p>
</div>
</a>
</li>
<?php endwhile; ?>
</ul>※当サイトでは初期値とデフォルト値の言葉の定義を区別せず、原則統一して初期値を採用しています。