この記事では、1年以上前に書かれた記事です。状況は今異なっている可能性があることに注意してください。
WP_Queryで投稿記事をループして出力する際、どうしてもショートコードが実行されない。
調べてみると、hava_posts()を使ってthe_content()で出力するのが一般的らしい。
しかしショートコード内で出力するには、the_contentで出力したくない。
return変数に渡すには、変数をdo_shortcode()に通せば出力できることが判明した!
ダメなケース
1 2 3 4 5 6 7 8 9 10 |
function test_get_post() { $query = new WP_Query($args); $posts = $query->posts; foreach ($posts as $post) { $html .= $post->post_title; $html .= $post->nl2br($post->post_content); } return $html; } add_shortcode('hoge_get_post','test_get_post'); |
修正後
1 2 3 4 5 6 7 8 9 10 |
function test_get_post() { $query = new WP_Query($args); $posts = $query->posts; foreach ($posts as $post) { $html .= $post->post_title; $html .= do_shortcode($post->nl2br($post->post_content)); } return $html; } add_shortcode('hoge_get_post','test_get_post'); |