問題描述

我不知道為什麼,但我已經使用 get_posts()查詢一些資料。然後我使用 setup_postdata() … 我認為它的使用,所以我可以使用像 the_permalink()等功能與新的帖子資料?

<?php foreach ($childPosts as $cp) : setup_postdata($cp); ?>

<article <?php post_class() ?> id="post-<?php the_ID(); ?>">
  <h1><a href="http://<?php%20the_permalink()%20?>"><?php the_title(); ?></a></h1>
  <?php if (has_post_thumbnail()) : ?>
  <a href="http://<?php%20the_permalink()%20?>"><?php the_post_thumbnail(($hasOutputNotFeaturedDiv) ? 'thumb-small' : null) ?></a>
  <?php endif; ?>
  <?php the_excerpt(); ?>
  <p class="more"><a href="http://<?php%20the_permalink()%20?>">Read more ...</a></p>
  <?php include (TEMPLATEPATH . '/inc/meta.php' ); ?>
</article>

<?php endforeach; ?>

但似乎只有 the_excerpt 包含新的後期資料值,為什麼呢?我發現如果我使用 echo get_the_permalink($cp)它可以正常工作。但我認為較短的版本會更好

最佳解決方案

我可能是錯的,但從我看到的,”setup_postdata()” 應該用於做一個自定義選擇查詢 (不只是 query_posts):http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query

同樣,如果要使用”the_title()” 和”the_permalink()” 等標籤與該自定義選擇查詢一起使用… 您需要在 setup_postdata() 中使用變數名稱 (不是另一個變數名) – 至少應該呼叫 global $ post 在您的”foreach” 迴圈之前…

所以基本上遵循那個抄送連結的例子。並且不要更改變數名 $ post – 否則它會中斷它。

HTH

次佳解決方案

更換

foreach ( $childPosts as $cp ) : setup_postdata( $cp );

foreach ( $childPosts as $post ) : setup_postdata( $post );

因此,您需要使用精確的 $post 變數以及 setup_postdata()

第三種解決方案

根據你在哪裡使用 setup_postdata()(如果它不在主迴圈中,或者在函式/側邊欄小工具中),你可能還需要宣告 –

global $post;

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。