I'm using get_posts()
to fetch posts from a particular category to display at the top of my homepage, separate from the main homepage Loop. Everything seems to work fine, but for the title (returned through the_title()
) which is always the same; the title of the first post fetched by get_posts()
. the_permalink()
does the same as well, but the_excerpt()
returns the correct result for each post.
Here's my code (I have removed only a few lines for fear I might inadvertently remove what is causing this problem):
$query = get_posts(array(
'numberposts'=>-1,
'category'=>3
));
$events = array();
if ($query) {
foreach ($query as $tpost) {
$fields = get_post_custom($tpost->ID);
if (isset($fields['event_start'])) {
$usetime = $fields['event_start'][0];
if (isset($fields['event_end'])) {
$usetime = $fields['event_end'][0];
}
if ($usetime>time()) {
$events[] = array("post"=>$tpost,"fields"=>$fields);
}
}
}
usort($events,function($a,$b){
$a = $a['fields']['event_start'][0];
$b = $b['fields']['event_start'][0];
if ($a==$b) { return 0; }
return ($a < $b) ? -1 : 1;
});
}
if (count($events)>0) { ?>
<div class="pad10 tac">
<h2 class="mar10">Upcoming Events</h2>
<div class="tiles">
<?php foreach ($events as $event ) { ?>
<?php setup_postdata( $event['post'] );?>
<a href="<?php the_permalink(); ?>" class='noshow'>
<div class="tile smalltile"><div id='post-<?php the_ID(); ?>'>
<h2><?php the_title();?></h2>
<b><?php
echo(date_i18n("D, F j @ g:ia",$event['fields']['event_start'][0]));
?></b>
<p><?php the_excerpt();?></p>
</div></div>
</a>
<?php }?>
</div></div>
<?php }?>
I'm really scratching my head on this, especially as this code is, for the most part, based off of the get_posts()
example from this article, where it is reportedly working fine.
I'm thinking that this likely has something to do with my use of setup_postdata, but I suppose this is really just wild speculation.
setup_postdata()
explains why this doesn't work and how to fix it.