WEB制作のための情報サイト / unazuki Library

get_the_excerpt()

基本構文と使い方(引数・実行結果)

記事の抜粋分を取得します。抜粋の長さはデフォルトで110文字(日本語)です。

基本構文

get_the_excerpt($post);

引数

引数必須/任意引数に指定するもの
第1引数
$post
任意判定したい記事のID (整数)/ オブジェクト
初期値null(結果的に現在の記事の抜粋文を取得)

実行結果

戻り値(返す値):記事の抜粋文
※表示するにはechoします。

例1.抜粋文を取得する

引数を指定しない場合、現在の記事の抜粋文を取得します。

get_the_excerpt();

例2.指定したIDの記事の抜粋文を取得する

下記の例では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>

※当サイトでは初期値とデフォルト値の言葉の定義を区別せず、原則統一して初期値を採用しています。

関連するテンプレートタグ

テンプレートタグ 説明
post_class() 投稿に関するclass名を表示する。
the_author() 現在の記事の投稿者の名前を表示します。
get_the_author() 現在の記事の投稿者の名前を返します。
the_ID() 現在の記事のIDを表示します。
get_the_ID() 現在の記事のIDを取得します。
get_post_meta() カスタムフィールドの値を取得します。
the_permalink() 記事のパーマリンク(URL)を表示します。
get_permalink() 記事のパーマリンク(URL)を表示します。
the_post_thumbnail() 記事にアイキャッチ画像がある場合は、アイキャッチ画像を表示する。
get_the_post_thumbnail() 記事にアイキャッチ画像がある場合は、アイキャッチ画像を含むimg要素を返す。
has_post_thumbnail() 投稿にアイキャッチ画像があるかないかを判定した結果、真偽値(true / false)を返す。
the_content() 記事本文を表示します。moreタグ(続きを読むタグ)を使っている場合は、引数の指定次第で記事の一部を表示します。
get_the_content() 記事本文のHTMLを取得します。moreタグ(続きを読むタグ)を使っている場合は、引数の指定次第で記事の一部を取得します。
the_excerpt() 記事の抜粋分を表示します。抜粋の長さはデフォルトで110文字(日本語)。
the_time() 記事の公開時刻を表示します。
get_the_time() 記事の公開時刻を取得します。
the_date() 現在の記事(投稿や固定ページ)の公開日を表示します。
get_the_date() 記事(投稿や固定ページ)の公開日を取得する。
the_title() 記事のタイトルを表示します。
get_the_title() 記事のタイトルを取得します。