0

My loop shows a list of values, and underneath them, the post title and image for the value.

The problem is that because some values are associated with multiple posts, multiple images show up. I only need one image. Is there any way to show only the first image in my foreach loop?

Here's my code:

<?php 
$the_query = new WP_Query(array(
    'post_type'     => 'post',
    'post_status'   => 'publish',
    'meta_key'      => 'colors',
));

$results = [];
while ( $the_query->have_posts() ) {

    $the_query->the_post(); 
    $credits = get_field('colors');

    if( !empty($color) ) {

        foreach( $colors as $color ) {  
           $results [$color][]=array(
               'title' => get_the_title(),
               'img' => get_field('photo')
           );
       }
    }
}

foreach ($results as $color => $posts) {

   foreach($posts as $post) {  /* This shows multiple images but I only need one */
        echo '<img src="'.$post['img']['url'].'">';
    }


   echo '<div><h2>'.$color.'</h2>';

    foreach($posts as $post) {
        echo '<div>'.$post['title'].'</div>';
    }

   echo '</div>';
}

wp_reset_postdata();?>
1

Depending of what you are exactly trying to achieve accessing the first element of the $posts array may work for you. No need for the foreach loop.

echo '<img src="'.$posts[0]['img']['url'].'">';
  • 1
    Yes, this is working! Thank you – BlueHelmet Jun 1 at 20:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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