Hi,
On a single page i list related posts by category at the bottom. And it’s working fine for most stuff, like featured image, date and so on. But for some reason get_the_excerpt isnt working the same way, every related post shows the excerpt of the current post.
Here is the code for my related post section:
<?php
global $post;
$cat_ID=array();
$categories = get_the_category();
foreach($categories as $category) {
array_push($cat_ID,$category->cat_ID);
}
$args = array(
'post_type' => 'news',
'post__not_in' => array($post->ID),
'category__in' => $cat_ID,
'showposts' => -1
);
$cat_posts = get_posts($args);
if($cat_posts) {
?>
<div class="posts">
<?php $i = 1; ?>
<?php echo '<div class="post-row"><div class="row">'; ?>
<?php foreach ($cat_posts as $cat_post) { ?>
<a href="<?php echo get_the_permalink($cat_post->ID); ?>" class="small-12 medium-4 columns end post">
<figure class="post-thumbnail">
<?php echo get_the_post_thumbnail($cat_post->ID, 'thumbnail'); ?>
</figure>
<div class="post-inner">
<h3 class="post-title"><?php echo get_the_title($cat_post->ID); ?></h3>
<p class="post-date"><i class="icon-clock"></i><?php echo get_the_time('M j, Y', $cat_post->ID); ?></p>
<div class="post-excerpt"><?php echo get_the_excerpt($cat_post->ID); ?></div>
</div>
<span class="btn btn-small">Read more</a>
</a>
<?php if($i % 3 == 0) { echo '</div></div><div class="post-row"><div class="row">'; } ?>
<?php $i++; } ?>
<?php echo '</div></div>'; ?>
</div>
<?php } ?>
Anyone know why and what changes I have to make?
EDIT: by changing to <?php echo $cat_post->post_excerpt; ?> i manage to retrieve the correct excerpt, BUT if there is no excerpt nothing is shown, if nothing is written in the excerpt field I want it to take the first words from the_content just like how the_excerpt(); usually works.
EDIT2: Solved it by changing to: <?php foreach ($cat_posts as $post) { setup_postdata( $post ); ?> and adding wp_reset_postdata(); ?> after the enforeach.