問題描述

此程式碼來自我的頁面 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。