問題描述
此代碼來自我的頁面 single-publication.php 。
它輸出相關的自定義字段等 (這裏包含在模板標籤中),但 the_content()不會輸出帖子內容。我已經訴諸於使用 $post->post_content(它的作品),但是這個奧秘依然存在:
<div class="publication-info">
<?php printf("<h2>%s</h2>", get_the_title() ); ?>
<div class="publication-meta publication-credit"><?php the_publication_credit(); ?></div>
<div class="publication-meta publication-date"><?php the_publication_date(); ?></div><br />
<div class="publication-blurb" style="font-family:sans-serif;"><?php echo $post->post_content; // the_content() doesn't work. Why not? ?></div>
</div>
這裏發生了什麼?
編輯:我被問到這個問題,因為我相信 – 錯誤地説,事實證明,$post 的工作和 get_the_title()返回一個標題是循環中的一個鐵皮標誌。但顯然不是這樣。 cf Codex on The Loop(第二段) 和 Codex on get_the_title()(參數表) 。有人可以解釋嗎
最佳解決方案
一些 post-related 數據默認不可用於 get_posts,例如通過 the_content()發佈的內容或數字 ID 。這通過調用內部函數 setup_postdata()解決,$ post 數組作為其參數:
<?php
$args = array( 'posts_per_page' => 3 );
$lastposts = get_posts( $args );
foreach ( $lastposts as $post ) :
setup_postdata( $post ); ?>
<h2><a href="<?php%20the_permalink();%20?>"><?php the_title(); ?></a></h2>
<?php the_content(); ?>
<?php endforeach;
wp_reset_postdata();
?>
請參閲訪問所有帖子數據
次佳解決方案
你的 HTML 很有可能不被包含在循環中。確保您的代碼如下所示:
if(have_posts()): while(have_posts()): the_post(); ?>
<div class="publication-info">
<?php printf("<h2>%s</h2>", get_the_title() ); ?>
<div class="publication-meta publication-credit"><?php the_publication_credit(); ?></div>
<div class="publication-meta publication-date"><?php the_publication_date(); ?></div><br />
<div class="publication-blurb" style="font-family:sans-serif;"><?php echo $post->post_content; // the_content() doesn't work. Why not? ?></div>
</div>
<?php endwhile; endif;
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。