2012-05-23 36 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,而是一个页面模板。 –

相关问题