In a loop, output only posts having a featured image


I want to show the 3 latests posts with a featured image (and exclude those without a feat image).
So i create a loop and add a conditional inside like this:

<Loop type=post count=3 orderby=title>
  <If field=image>
    <Field image />
    <Field title />

My problem: it renders only 1 post… because the 2 following have no featured image and are excluded.

If i modify the posts order, with order=desc for instance, it renders 2 posts (the third has no img): still not 3 posts.

So, i understand that the “holes” let by the excluded posts in the loop are not filled by the following posts with a feat image.

Maybe my conditional is not correct?

Found something, it seems the conditional can be set in the <Loop> tag itself:

<Loop type=post count=3 orderby=title field=image_url field_compare=exists>

First i tried to evaluate field=image, it didn’t work but does work with field=image_url

Please, add more examples to the doc, it was a great help in CCS. :wink:
But obviously, thanks a lot for Loops & Logic, it rocks!

I suppose technically, the loop is behaving as it should: it gets 3 posts (regardless of featured image), then filters them by the If condition.

Could you see if the following works like you want?

<Loop type=post count=3 orderby=title field=image>
    <Field image />
    <Field title />

Hi @eliot,

Thanks for your answer.
You’re right, the posts filtering has to be done in the loop tag.

But this works:

<Loop type=post count=3 orderby=title field=image_url field_compare=exists>

…and this doesn’t work, it returns posts without featured image (field=image seems unefficient) :

<Loop type=post count=3 orderby=title field=image>

Good to know. I see the second example doesn’t work (yet) because the field image returns an instance of attachment loop with no items. I’ll improve this in the next version so that it’s recognized as empty, as expected.

For now, I think any image field with string or number value should work, without field_compare attribute (whose default value is exists). Like:

<Loop type=post count=3 orderby=title field=image_id>

In your example, field=image_id would work for an image in a custom field, but not WP regular featured image, correct?

image_id would be an ACF key for instance?

Anyway, thanks a lot for taking my request into account. :wink:

Actually, I believe it’s the other way around: field=image_id should work for WP core’s featured image field, but not for ACF image field type.

In the future, it might be possible to support the latter with acf_image=field_name, and other acf_* attributes in the Loop tag.

Perfectly right, field=image_id as the filter works by excluding posts without a WP featured image from the loop.
That’s what i was looking for, thank you!

1 Like