I'm trying to show images contained within the_content()
in a specific way. I've already managed to extract the images url path with DOMDocument()
as follows:
<?php
$content = get_the_content();
$dom = new DOMDocument;
if ($dom->loadHTML($content)) {
$imgs = $dom->getElementsByTagName('img');
if ($imgs->length > 0) {
foreach ($imgs as $img) {
$img->getAttribute('src');
}
}
}
?>
Echoing the $img
array shows that the code above is working correctly. What I need now is to loop through the array and print each array element into a <img>
tag src
field. The following prints blank links:
<?php foreach ($imgs as $img) { ?>
<a class="fancybox" rel="galeria1" href="<?php echo htmlentities($img); ?>" title="teste">
<img class="img-responsive" src="<?php echo htmlentities($img); ?>" alt="" width="474" height="315"></a>
<?php } ?>
Thank you in advance.
Not sure if I'd do it that way, it's quite a messy implementation IMO, but to answer your question:
To display the image you need to grab what value is inside the actual image:
$img
Like so:
$img->getAttribute('src')
It looks like you've done this in your first example but not your second ?
Your second example should look like this:
<?php foreach ($imgs as $img) { ?>
<a class="fancybox" rel="galeria1" href="<?php echo $img->getAttribute('src'); ?>" title="teste">
<img class="img-responsive" src="<?php echo $img->getAttribute('src'); ?>" alt="" width="474" height="315"></a>
<?php } ?>