Displaying images based on the custom field

<?php foreach($page->images() as $image): ?>
	<?php if($image->section()->kirbytext() ==="2"):?>
		    <div class="col-lg-3 col-md-4 col-xs-6 thumb">
		         <a class="thumbnail" href="<?php echo $image->url() ?>">
		            <img class="img-responsive" src="<?php echo $image->url() ?>" alt="">
		         </a>
		    </div>
	<?php endif ?>
<?php endforeach ?>

I’ve a custom field in images named as section and each of the images have numbers, I assigned many images with number 2 and tried to execute the code above but failed.

The loop works fine without the logical IF statement

You’re calling the kirbytext() method on your field, causing it to be interpreted as markdown text— it ends up comparing the strings <p>2</p> and 2, and failing.

Try replacing that with toInt()! This will coerce the field into an integer. Then, take off the quotes from your "2" to do an integer comparison.

Tried toInt() and removed the quotes but it doesn’t seem to show the images which has 2 as section.

Try

if($image->section()->value() == 2) {
  //do stuff
}
1 Like

Awesome, This works like a charm, Thanks alot