从类别中的最新帖子获取ID以用于类别档案 [英] Get id from latest post in category to use in category archives

查看:71
本文介绍了从类别中的最新帖子获取ID以用于类别档案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取每个类别中最新帖子的ID,并使用该ID获取元信息和缩略图并将其显示在相应类别的旁边。我只是不确定该怎么做。

I'm trying to get the id of the latest post in each category, and use that id to get the meta info and thumbnail and display it next to the corresponding category. I'm just not sure how to do it.

我一直在尝试这段代码,但是它对我不起作用:

I've been trying this code, but it isn't working for me:

<?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; ?>

我在做什么错了?

推荐答案

除一行之外,您所看到的一切都正确。您需要更改:

Everything you have looks correct, except for one line. You need to change:

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

收件人:

'category' => $category->cat_ID

类别对象没有'id'属性,而是' cat_ID'属性。

Category objects do not have an 'id' property, but rather a 'cat_ID' property.

添加:如果出于某种原因不能解决您的问题,那么我唯一想到的另一件事就是更改此行:

ADDITIONALLY: If for whatever reason that doesn't solve your problem, the only other thing I can think of would be to change this line:

$randpostid = ($randpost->ID);

收件人:

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

get_posts()返回一个数组,但是我不确定单个时它是否为数组格式帖子被退回。无论哪种方式,第一次代码更改都是必须的,而第二次代码则可能是必需的。

get_posts() returns an array, but I'm not sure if it is in array format when single posts are returned. Either way, the first code change is a must, and the second is probably needed.

这篇关于从类别中的最新帖子获取ID以用于类别档案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆