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="https://wordpress.stackexchange.com/questions/174962/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="https://wordpress.stackexchange.com/questions/174962/<?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
2 s
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.