WordPress Template customization > Related Posts Loop outputting from current post

So I’m trying to output a loop with 3 posts from the same category. It seems to be pulling everything correctly except when it outputs the loop for each item only the get_the_content is correct. The other data (image, title, link) are outputing the values for the current post.

So basically I need to get this loop get the correct values for the_post_thumbnail and the_title and get_permalink.

<?php
/**
 * The template used for displaying page content
 *
 * @package WordPress
 * @subpackage Twenty_Fifteen
 * @since Twenty Fifteen 1.0
 */
?>

<?php
$related = get_posts( array( 'category__in' => wp_get_post_categories($post->ID), 'numberposts' => 3, 'post__not_in' => array($post->ID) ) );
if( $related ) {
?>
<div class="related-posts">
    <h2>Related Posts</h2>
<?php    foreach( $related as $related_post ) {
        setup_postdata($related_post);
?>
<article>

    <div class="post-thumbnail">
        <?php the_post_thumbnail('thumbnail'); ?>
    </div><!-- .post-thumbnail -->

    <?php the_title( '<h3>', '</h3>' ); ?>
    <p>
    <?= wp_trim_words( get_the_content(), 10, '<a href="'. get_permalink() .'"> Read More...</a>' ); ?>
    </p>

</article>
<?php        
    }
?>
</div>    
<?php 
} 
wp_reset_postdata();
?>

Related posts

Leave a Reply

1 comment

  1. You are facing problem due to setup_postdata function. This function takes an object as argument and it should be $post.

    Check the documentation. https://codex.wordpress.org/Function_Reference/setup_postdata

    <?php
    $related = get_posts( array( 'category__in' =>     wp_get_post_categories($post->ID), 'numberposts' => 3, 'post__not_in' => array($post->ID) ) );
    if( $related ) {
    ?>
    <div class="related-posts">
        <h2>Related Posts</h2>
    <?php
      global $post;
      foreach( $related as $post ) {
    
            setup_postdata($post);
    ?>
    <article>
    
        <div class="post-thumbnail">
            <?php the_post_thumbnail('thumbnail'); ?>
        </div><!-- .post-thumbnail -->
    
        <?php the_title( '<h3>', '</h3>' ); ?>
        <p>
    <?= wp_trim_words( get_the_content(), 10, '<a href="'. get_permalink() .'"> Read     More...</a>' ); ?>
        </p>
    
    </article>
    <?php
        }
    ?>
    </div>
    <?php
    }
    wp_reset_postdata();
    ?>