I am having trouble adding a caption to my images. I want to add a caption to an image if it has one. However, the page/loops stops after the first image. What am I doing wrong?
<ul>
<?php foreach($page->images()->filterBy('filename', '!=', 'thumb.jpg')->sortBy('sort', 'asc') as $img): ?>
<li><img src="<?php echo $img->url() ?>" alt="Image" class="img-responsive"/>
<?php if ($image->caption() != ''): ?>
<p class="caption"><?php echo kirbytext($image->caption()) ?></p>
<?php endif ?>
</li>
<?php endforeach ?>
</ul>
Thanks for the help.
You’re trying to access the caption of $image
instead of $img
. This should work.
<ul>
<?php foreach($page->images()->filterBy('filename', '!=', 'thumb.jpg')->sortBy('sort', 'asc') as $img): ?>
<li><img src="<?php echo $img->url() ?>" alt="Image" class="img-responsive"/>
<?php if ($img->caption() != ''): ?>
<p class="caption"><?php echo kirbytext($img->caption()) ?></p>
<?php endif ?>
</li>
<?php endforeach ?>
</ul>
Note: It’s recommended to use a figure to semantically attach a caption to an image.
This is the figure tag: http://www.w3schools.com/tags/tag_figure.asp
This is the figcaption tag: http://www.w3schools.com/tags/tag_figcaption.asp
That worked. Thanks for catching that error. Also, thank you for the code feedback. Development is not my strength, but I am always looking for ways to improve.
1 Like
There’ll always be someone here to help if you have any more questions