8

I have posts whose each contains 4 attached images. what i'm trying to do in my single.php is to get all the 4 images src to be abble to add different classes to each images.

<img class="image_1 no_lazy" src="first attached image src"/>
<img class="image_2" src="second attached image src"/>
<img class="image_3" src="third attached image src"/>
<img class="image_4" src="fourth attached image src"/>

here is what I've tried, but I get an array instead of getting the src... I think I'm really close to the solution, but I can't find out what I am doin wrong...

<?php
  global $post;
  $args = array( 
    'post_parent' => $post->ID, 
    'post_type' => 'attachment', 
    'post_mime_type' => 'image', 
    'orderby' => 'menu_order', 
    'order' => 'ASC', 
    'numberposts' => 4 );
   $images = get_posts($args); ?>

<img class="image_1 no_lazy" src="<?php  echo wp_get_attachment_image_src( $images[0]->ID, 'full' ); ?>"/>
<img class="image_2" src="<?php  echo wp_get_attachment_image_src( $images[1]->ID, 'full' ); ?>"/>
<img class="image_3" src="<?php  echo wp_get_attachment_image_src( $images[2]->ID, 'full' ); ?>"/>
<img class="image_4" src="<?php  echo wp_get_attachment_image_src( $images[3]->ID, 'full' ); ?>"/>

can anybody help me with this ?

thanks

13

If you only want to add an extra class, then you should use wp_get_attachment_image. It has few extra params, and the last one is used for setting class names.

Sample usage:

<?php echo wp_get_attachment_image( get_the_ID(), 'thumbnail', "", ["class" => "my-custom-class"] ); ?>

The main advantage of this aproach is that you will also get the whole srcset attributes for free.

0

wp_get_attachment_image_src returns an array with 3 elements; the image URL, the width, and the height. You need to echo the first index of the result.

In fact, you can make your code a little leaner by using a foreach loop:

foreach ( $images as $i => $image ) {
    $src = wp_get_attachment_image_src( $image->ID, 'full' );

    echo '<img class="image_' . ++$i;
    if ( $i === 1 )
        echo ' no_lazy';
    echo '" src="' . $src[0] . '" />';
}
  • if you just need the URL you can use wp_get_attachment_image_url() – iantsch Mar 14 '16 at 17:58

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.