2015-07-20 29 views
2

我想獲得最新的WordPress的帖子在我的網站的頂部和這篇文章下面,我試圖顯示所選頁面的內容。例如如果用戶在「首頁」上,則應顯示最新帖子,並在其下方顯示「主頁」的內容。要獲取最新帖子,我正在使用wp_get_recent_posts()並顯示我正在使用的網頁內容the_content()使用wp_get_recent_posts()和the_content()在同一時間使用wordpress

這是我最新的郵編:

<div id="news"> 
    <?php 
     $posts = wp_get_recent_posts(array('numberposts' => 1, 'post_type' => 'post')); 

     foreach($posts as $post){ 
      echo '<p>' . $post["post_content"] . '</p>'; 
     } 
    ?> 
</div> 

,並顯示出我使用這個代碼的頁面內容:

<h2><?php the_title(); ?> </h2> 
<div id="postcontent"> 
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?> 
    <p><?php the_content(); ?></p> 

    <?php endwhile; ?> 
    <?php endif; ?> 
</div> 

我的問題是:它不顯示頁面內容。如果我評論「新聞」部分,它會顯示頁面內容。看起來這些代碼部分不能同時工作。有沒有其他選擇,或者我的代碼中有什麼問題?

回答

1

wp_get_recent_posts()就像get_postsget_pages只是返回來自WP_Query的自定義實例的對象,而不是完整的查詢對象。這意味着,您不能使用由WP_Query返回的默認查詢對象來運行正常循環,因此,默認情況下,使用前三個函數中的任何一個都不會設置postdata。

設置postdata非常重要,因爲這使得可以使用模板標籤。正如你所知道的那樣,設置postdata需要設置全局的$post注意:任何其他變量都不會工作),所以這就是我們將要使用的。 (注:請不要使用$posts全局作爲變量,你破壞了全球

$args = [ 
    // Some arguments 
]; 
$posts_array = wp_get_recent_posts($args); 
foreach ($posts_array as $post) { 
    setup_postdata($post); // This is the important line, and you have to use $post 
    the_content(); 
} 
wp_reset_postdata(); // Very important, restores the $post global 
+0

非常感謝:)它按預期工作。我注意到我的代碼的另一種選擇是重命名'$ posts'和'$ post'。 – Tyler

+0

對不起,被'get_posts'帶着帶走 –

+0

如果你堅持你的方法是,但是如果你使用'setup_postdata',你必須使用'$ post' ;-) –

0

當你這樣做:

foreach($posts as $post) 

你覆蓋全球$post對象。

在你的循環之後使用wp_reset_postdata(),因此它會將$post對象重置爲主查詢的一個。

+0

謝謝您的回答,但'wp_reset_postdata()如預期'不起作用。還有其他建議嗎? – Tyler

相關問題