LoginSignup
11
11

More than 5 years have passed since last update.

Wordpressのget_post関数のpost_contentで段落タグが抜けないようにする方法(the_content関数と同じ結果で出力する方法)

Last updated at Posted at 2016-03-16

はじめに

Wordpressのget_post関数を使用すると、投稿や固定ページに関する値を取得することができますが、その
post_contentオブジェクトより出力される結果には、段落タグが含まれません。(ただし、Wordpressのエディタのテキストモードで<p></p>ように明示的に入力された場合を除きます)

このため、post_contentオブジェクトの値をそのままechoすると、レイアウトが崩れてしまう等、意図しない表示結果(the_content関数の出力とは異なる結果)となる場合があります。

原因

Wordpressのエディタで編集した内容では、段落は段落タグ(<p></p>)ではなくそのまま改行コードで保存されます。

the_content関数を使用する場合は、出力の際にthe_contentフィルターが適用されますので、改行が<p></p>に置き換えられます。しかし、get_post関数のpost_contentオブジェクトの出力結果にはthe_contentフィルターが適用されませんので、the_content関数のように改行が置き換えられずに(DBに記録された通りにそのまま)出力されます。

対応方法

post_contentオブジェクトの出力結果に対して、the_contentフィルターを適用することで、the_content関数と同様の出力結果となります。

example.php
$post_id = 1;
$post = get_post($post_id);
echo apply_filters('the_content',$post->post_content);
11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11