2017-04-24 134 views
1

我有一個靜態頁面有10個容器位於index.php文件中的不同位置,我想顯示10個最新的帖子。我想反映了對一個職位的數據(標題,文字,縮略圖,作者,時間)是這樣的:WordPress的打印最新帖子

 <div class="text"> 
     <?php 
      echo '$textfrompost3'; 
     ?> 
    </div> 

<div class="title"> 
    <?php 
     echo '$titlefrompost3'; 
    ?> 
    </div> 

     ... 
     ... 

我的PHP文件:

<?php 
    // the query 
    $the_query = new WP_Query(array(
    'category_name' => 'Allgemein', 
     'posts_per_page' => 10, 
     "orderby"  => "date", 
     "order"   => "DESC" 
    )); 

?> 

<?php if ($the_query->have_posts()) : ?> 
    <?php while ($the_query->have_posts()) : $the_query->the_post(); ?> 



    // insert values into variables 


    <?php endwhile; ?> 
    <?php wp_reset_postdata(); ?> 


<?php endif; ?> 

在此先感謝,我很欣賞你的幫助可以提供。

+0

可能的[如何顯示最新的帖子WordPress的]重複(HTTP ://stackoverflow.com/questions/41631565/how-to-display-latest-posts-wordpress) –

+0

不工作,因爲它打印在一個循環下彼此的帖子我想要的變量中的10個最新帖子的數據或別的東西 –

+0

然後試試這可能嗎? https://wordpress.stackexchange.com/questions/217299/wp-query-results-stored-in-variables - 多數民衆贊成什麼谷歌返回時搜索「WP_QUERY結果變量」 –

回答

1

我只是簡單地用WP_Query替換你的電話get_posts()這將提供一個post對象數組。

$latest_posts = get_posts(array(
    'category_name' => 'Allgemein', 
    'posts_per_page' => 10, 
)); 

我已經下降在上面的例子中orderorderby。儘管您可能有不同的全局設置來顯示帖子數量,但您不太可能修改默認排序。

文檔:https://codex.wordpress.org/Template_Tags/get_posts

所以我們可以說我要輸出的第三文章的標題,我可以做到以下幾點:

// let's be sure we have a third post. 
if (isset($latest_posts[2])) { 
    echo $latest_posts[2]->post_title; // remember arrays have a zero-based index. 
} 
+0

如何獲得帖子作者或縮略圖? :/ post_author不存在。我想使用get_the_author等,但它不工作。 –