Select newest post in foreach loop

hey. so I have a foreach loop that displays the newst post of 5 different tags. so it shows the newest post of tag-1, tag-2, etc.

        <div class="row">
            {{#get "posts" limit="5" filter="tag:[tag-1,tag-2,tag-3,tag-4,tag-5]" order="asc"}}
            {{#foreach posts}}
                <div class="post">
                <a href="{{url}}">
                    <img src="{{feature_image}}" alt="{{title}}">
                    <h3>{{title}}</h3>
                </a>
                </div>
            {{/foreach}}
            {{/get}}
        </div>

Now, I’d like to implement something that picks out the most recently published post of the five displayed and give its an extra “newest” class. Is it possible to do this in handlebars, or do I need to do it via client-side javascript?

The code you posted doesn’t do what you say. You’re going to get whichever five are newest with any of those tags, not one newest fir each tag….

Yeah, that’s true, however, for my usecase that doesn’t matter, since they should always be published after each other. I guess a more stable way would be to do a seperate loop for each tag. Still, that doesn’t solve the issue with catching the newest one…

If you fix your order to sort by “published_at desc”, you’ll get the most recent post first and can use the @first helper. (Your current order setting looks invalid.)

yeah, but I want them to remain in the order they currently are, which is tag-1 on the left, tag-5 on the right, so I don’t want a “published_at” order. Is it possible to pull in all the publish dates, pick the latest one and give an extra class to a div?

The code you have should be giving you the published at order — that’s the default.

But if you want to order them by prinary_tag instead (which might be happening by accident right now), you could instead set an attribute within outer div for the post and then use JavaScript to get those values and style them.

<div class=“post” data-date=“{{published_at}}”

(Typed on my phone - you may need to fix the quotes!)

1 Like