2012-05-23 33 views
0

我想要獲取每個類別中的最新帖子的id,並使用該id獲取元信息和縮略圖,並顯示它旁邊的相應類別。我只是不知道該怎麼做。從類別檔案中的類別的最新帖子獲得id

我一直想這個代碼,但它不是爲我工作:

<?php 
$args=array(
    'orderby' => 'name', 
    'order' => 'ASC' 
); 
$categories=get_categories($args); 
foreach($categories as $category) : ?> 

    <?php $randpost = get_posts(
     array(
      'numberposts' => 1, 
      'category' => array(get_query_var($category->id)), 
     )); 
    $randpostid = ($randpost->ID); 
    ?> 

    <?php echo '<h2 class="newsitem"><a href="' . get_category_link($category->term_id) . '" title="' . sprintf(__("View all posts in %s"), $category->name) . '" ' . '>' . $category->name.'</a> </h2> '; ?> 
    <?php echo '<p>'. $category->count . ' nummer</p>'; ?> 

    <strong>Stad:</strong> 
    <?php $city = get_post_meta($randpostid, 'city', true); ?> 
    <?php echo $city ?> 

<?php endforeach; ?> 

我在做什麼錯?

回答

1

一切看起來是正確的,除了一條線。您需要更改:

'category' => array(get_query_var($category->id)), 

要:

'category' => $category->cat_ID 

類別對象沒有一個 '身份證' 屬性,而是一個 'CAT_ID' 屬性。

此外:如果因任何原因不解決您的問題,我能想到的唯一的另一件事是改變這一行:

$randpostid = ($randpost->ID); 

要:

$randpostid = ($randpost[0]->ID); 

get_posts()返回一個數組,但我不確定返回單個帖子時它是否是數組格式。無論哪種方式,第一次代碼更改是必須的,第二次可能是需要的。

+0

解決了它,非常感謝!我一整天都在b my我的頭。 –

0

如果您剛剛顯示最新帖子的信息,您可能會以更簡單的方式做到這一點。像這樣的事情在你的頁面模板應該工作(未經測試):

編輯

答案在OP評論的光編輯:你有

<?php 
$cat_args = array('orderby' => 'name','order' => 'ASC'); //for parameters see http://codex.wordpress.org/Function_Reference/get_categories 

$categories=get_categories($cat_args); 

foreach($categories as $category) { // for each category we as for the most recent post 

$post_args = array('numberposts' => 1, 'category' => $category, 'orderby' => 'post_date', 'order' => 'DESC',); 

$posts_array = get_posts($post_args); 

foreach($lastposts as $post) : setup_postdata($post); //Use setup_postdata to access parts of the object using regular WP template tags ?> 

    <?php post_id = get_the_ID(); // or you could just use $post->ID ?> 

    <!--Do your stuff here--> 

<?php endforeach; ?> 

<?php } ?> 
+0

這不是我以後的類別ID,它是每個類別內最新帖子的ID。然後,我打算使用該ID來獲取帖子縮略圖,元信息等,並將其顯示在相應類別旁邊。此外,剛剛意識到它不是我使用的category.php,而是一個頁面模板。 –

相關問題