get_the_content()


WordPressのget_the_content()関数は、投稿やページのコンテンツを取得するために使用されます。この関数は、コンテンツを返すだけで、直接出力はしません。

構文

get_the_content( string $more_link_text = null, bool $strip_teaser = false, WP_Post|object|int $post = null );

引数の説明:

  • $more_link_text (string) — 「続きを読む」リンクのテキストを指定します。デフォルトはnullです。
  • $strip_teaser (bool) — ティーザー部分を削除するかどうかを指定します。デフォルトはfalseです。
  • $post (WP_Post|object|int) — 取得する投稿のID、オブジェクト、またはWP_Postインスタンスを指定します。デフォルトはnullで、現在の投稿を取得します。

例1: 投稿のコンテンツを取得する

この例では、投稿のコンテンツを取得し、変数に格納します。

<?php $content = get_the_content(); echo $content; ?>

例2: 「続きを読む」リンクのテキストを変更する

「続きを読む」リンクのテキストをカスタマイズします。

<?php $content = get_the_content('もっと読む'); echo $content; ?>

例3: ティーザー部分を削除する

ティーザー部分を削除してコンテンツを取得します。

<?php $content = get_the_content(null, true); echo $content; ?>

例4: 特定の投稿のコンテンツを取得する

特定の投稿IDを使用してコンテンツを取得します。

<?php $content = get_the_content(null, false, 456); echo $content; ?>

例5: コンテンツをフィルタリングする

コンテンツを取得する前にフィルタを適用します。

<?php $content = get_the_content(); $filtered_content = apply_filters('the_content', $content); echo $filtered_content; ?>

例6: コンテンツを短い形式で取得する

コンテンツを短い形式で取得し、特定の文字数で切り詰めます。

<?php $content = get_the_content(); $short_content = wp_trim_words($content, 20); echo $short_content; ?>

例7: コンテンツをHTMLタグなしで取得する

コンテンツからHTMLタグを除去して取得します。

<?php $content = get_the_content(); $stripped_content = strip_tags($content); echo $stripped_content; ?>

例8: コンテンツをカスタムフィールドと組み合わせる

カスタムフィールドとコンテンツを組み合わせて表示します。

<?php $content = get_the_content(); $custom_field = get_post_meta(get_the_ID(), 'custom_field', true); echo $content . '<br>' . $custom_field; ?>

注意点

  • get_the_content()はコンテンツを返すだけで、直接出力しません。出力するにはechoを使用する必要があります。
  • 「続きを読む」リンクを使用する場合、投稿に<!--more-->タグが含まれている必要があります。
  • コンテンツをフィルタリングする場合、apply_filters()を使用してフィルタを適用することが重要です。

関連機能: