philsbury
philsbury

Reputation: 13

Timber get_posts in template/view

I have an ACF field that allows a choice of post types, these are then going to be put in a carousel. There could be any number as every module on the page is controlled by the admin users.

In the carousel template, I want to be able to get the recent posts for the selected post type. I can to this with:

{% set items = fn('get_posts', {'post_type': 'team' }) %}

Is there a way to do this without calling it as a function? I was thinking along the lines of:

{% set items = Posts(params) %}

Is this possible or is the function call the only/best way?

Thanks

Upvotes: 1

Views: 2111

Answers (1)

Gchtr
Gchtr

Reputation: 2794

Currently, what you want to do is not possible. You could use Timber::get_posts through the array notation to get an array of Timber posts instead of regular WordPress posts:

{% set items = fn(['Timber\Timber', 'get_posts'], { 'post_type': 'team' }) %}

But in the future, the recommended way to get posts will be to use Timber\PostQuery. In the upcoming version 2 of Timber, we will add a PostQuery function to Twig. This means that you’ll be able to do something like this:

{% for items in PostQuery(params) %}
    {# Display item #}
{% endfor }

This would work well for simpler use cases. I’d also recommend what Luckyfella said, it may be better to not have this in Twig at all, but prepare everything in PHP and then pass the items on to the Twig view.

Upvotes: 1

Related Questions