I have a Wordpress site and I want to put a header over-top the first image in a list/stack of images. I am using the following code to pull the images out of the text of the post content.
HTML
<?php
preg_match_all('/(<img [^>]*>)/', get_the_content(), $images);
for( $i=0; isset($images[1]) && $i < count($images[1]); $i++ ) {
echo $images[1][$i];
}
?>
This puts all the images in my post, One on top of the other (each pic is set to 100% width of screen and a specific height). I want to target the FIRST image so I can put
<h1><?php the_title(); ? ></h1 >
over-top of it. Not sure how to accomplish this
You can use the $i
to determine if you are looping on the first index or not.
<?php
preg_match_all('/(<img [^>]*>)/', get_the_content(), $images);
for( $i=0; isset($images[1]) && $i < count($images[1]); $i++ ) {
if ($i == 0) {
// only printed when looping on 1st image with a wrapped <div> element
echo sprintf('<div><h1>%s</h1>%s</div>', get_the_title(), $images[1][$i]);
continue;
}
echo $images[1][$i];
}
?>