0

Hi I have custom post and I am trying to print loop data in foreach loop. but one post is showing 4 time .any help

<?php $args = array( 'post_type' => 'service_slider', 'posts_per_page' =>5 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
  the_title();
  $thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ) );
  foreach ($thumbnail as $thumb){
  echo '<div class="item">';
  ?>
  <img class="thumbnail zoom" src="<?php  echo $thumbnail[0];?>" > 
 <?php
  echo '</div>';
  }
endwhile;
?>
2
  • Do you get duplicate images, or posts?
    – Johansson
    Commented Sep 19, 2017 at 10:04
  • Jack Johansson @yes I have one post but it's showing 4 post, when two then it's showing 8,any help
    – sanjay
    Commented Sep 19, 2017 at 10:07

1 Answer 1

0

You're trying to loop through the thumbnail, which doesn't make any sense:

foreach ($thumbnail as $thumb){

And then inside the loop you're referring to $thumbnail again anyway:

<img class="thumbnail zoom" src="<?php  echo $thumbnail[0];?>" > 

wp_get_attachment_image_src() returns an array that looks like this:

array(
    0 => 'http://website.com/path/to/image.jpg', // URL 
    1 => 150, // Width
    2 => 150, // Height
    3 => true // Is a resized version?
);

So when you try to loop through that, you're looping through those 4 values. But since you use $thumbnail[0] in the loop, it's just going to echo that first value 4 times.

And since you're doing this all inside while ( $loop->have_posts() ) : $loop->the_post(); you're going to echo the URL for the featured image 4 times for each post.

This would be the simplest approach:

$args = array( 
    'post_type'      => 'service_slider', 
    'posts_per_page' => 5
);

$loop = new WP_Query( $args );

while ( $loop->have_posts() ) : $loop->the_post();
    echo '<div class="item">';
    echo wp_get_attachment_image( get_post_thumbnail_id(), 'thumbnail', false, array( 'class' => 'thumbnail zoom' ) );
    echo '</div>';
endwhile; wp_reset_postdata();

while ( $loop->have_posts() ) : $loop->the_post(); is looping through the posts. You won't need a foreach at all. Then inside that loop I've output the item div and the post's featured image.

Note that I've used wp_get_attachment_image(), which outputs the fill image tag for the current post thumbnail (because I passed it get_post_thumbnail_id(). The 4th parameter lets you pass an image class to use. This function all also automatically pull in the alt text, which is good for accessibility.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.