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?
Everything you have looks correct, except for one line. You need to change:
To:
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:
To:
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.
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: