S.I.
S.I.

Reputation: 3375

Getting post featured image on different page

I want to show some custom posts on a page and their featured images. The problem is that the image of the first post is showed on all posts divs.

This is what I have so as a code

<?php
//solutions
$args = array(   
    'showposts'=>-1,
    'category_name' => 'Spage',
    'order' => 'ASC',
); 
$query = new WP_Query( $args ); 
$asPost = array();
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        $asPost[] = array('title' => $query->post->post_title,
                                   'content' => $query->post->post_content);
    }
}
?>

<?php $count = 0; ?>
        <?php if(!empty($asPost)){ ?>
             <?php foreach($asPost as $item){ ?>
                    <div class="container box<?php if( $count%3 == 0 ) { echo '-1'; }; $count++; ?>">
                        <div class="item">
                            <p class="headline font--h5 accent--teal"><?php echo $item['title']; ?></p>
                            <div class="fullwidth">
                                <?php the_post_thumbnail(); ?>
                            </div>
                            <div class="font--h5 body body--dark">
                                <?php echo apply_filters('the_content',$item['content']);?>
                            </div>
                        </div>
                    </div>
            <?php }?>
        <?php }?> 

How to take correct image?

Upvotes: 0

Views: 29

Answers (1)

Vel
Vel

Reputation: 9331

Try this code. I modified these 'id'=>$query->post->ID and <?php get_the_post_thumbnail($item['id']); ?> code.

$args = array(   
    'showposts'=>-1,
    'category_name' => 'Spage',
    'order' => 'ASC',
); 
$query = new WP_Query( $args ); 
$asPost = array();
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        $asPost[] = array('title' => $query->post->post_title,
                                   'content' => $query->post->post_content, 'id'=>$query->post->ID);
    }
}

?>

<?php $count = 0; ?>
        <?php if(!empty($asPost)){ ?>
             <?php foreach($asPost as $item){ ?>
                    <div class="container box<?php if( $count%3 == 0 ) { echo '-1'; }; $count++; ?>">
                        <div class="item">
                            <p class="headline font--h5 accent--teal"><?php echo $item['title']; ?></p>
                            <div class="fullwidth">
                                <?php get_the_post_thumbnail($item['id']); ?>
                            </div>
                            <div class="font--h5 body body--dark">
                                <?php echo apply_filters('the_content',$item['content']);?>
                            </div>
                        </div>
                    </div>
            <?php }?>
        <?php }?> 

Upvotes: 2

Related Questions