Get id from latest post in category to use in cate

2019-09-09 11:32发布

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

What am I doing wrong?

2条回答
Summer. ? 凉城
2楼-- · 2019-09-09 12:29

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

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

To:

'category' => $category->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);

To:

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

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.

查看更多
Lonely孤独者°
3楼-- · 2019-09-09 12:30

If you're just after displaying information from the most recent post you could probably do this in a much more simple fashion. Something like this in your page template should work (untested):

EDIT

Answer edited in light of OP comment:

<?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 } ?>
查看更多
登录 后发表回答