Getting posts with twig

Code

December 27, 2019

The Timber Posts Module allows you to perform a custom query, where you can set basic parameters for the returned posts. If the available settings aren’t enough, you will need to create your own Query Args.

Twig can manage

Because Twig is basically a template engine, you can programatically create the posts variable with a set of returned posts. In order to improve performance as much as possible, you can set WP Query setting to use “Main Query” and the Timber Query Method to “get_posts”, which is the fastest because no additional requests to enrich the results will me made.

Now you can move to the Template Tab of the Timber Posts Module.

Re-setting the posts variable

When the module is initialized, the posts variable is set with the Main Query as it’s results. Since we already know we won’t be needing those, the first thing to do is to reset it’s value:

{%
    set posts = fn( 'get_posts' , {
                                     'post_type' : 'post',
                                     'numberposts' : 5,
    } )
%}

Which, will get up to 5 posts from the default Posts.

Beaverplugins

Web ninja with PHP/CSS/JS and Wordpress skills. Also stand-in server administrator, father of four kids and husband to a beautiful wife.
Always spends too much time figuring out ways to do simple things even quicker. So that you can benefit.