Due to the setup of my template (and layout), I need to be able to place 4 different posts in 4 different divs.

For example, my structure would be like this

<div>Post 1</div>
<div>
    <div>Post 2</div>
    <div>
        <div>Post 3</div>
        <div>Post 4</div>
    </div>
</div>

But I’m having some trouble getting this to work, I use get_posts to get the 4 latest posts.

$posts = get_posts(array(
    'post_type' => 'post',
    'post_count' => 4
));  

And then I try to display my post

<?php setup_postdata($posts[0]); ?>
<?php get_template_part( 'template-parts/post-thumbnail' ); ?>
<?php wp_reset_postdata(); ?>

In template-parts/post-thumbnail.php I’m trying to display the title and permalink, but it’s always showing the title and link of the current page. Never of the actual post.

4 Answers
4

Your problem is that the variable passed to setup_postdata() must be the global $post variable, like this:

// Reference global $post variable.
global $post;

// Get posts.
$posts = get_posts(array(
    'post_type' => 'post',
    'post_count' => 4
));  

// Set global post variable to first post.
$post = $posts[0];

// Setup post data.
setup_postdata( $post );

// Output template part.
get_template_part( 'template-parts/post-thumbnail' );

// Reset post data.
wp_reset_postdata();

Now normal template functions, like the_post_thumbnail() inside the template part will reference the correct post.

Leave a Reply

Your email address will not be published. Required fields are marked *