So, I am beating my head over this for 2 days now. How do I display 3 recent posts in footer using Timber and Twig? I am using a starter theme from Timber. What I did inside my footer.php file:
$timberContext = $GLOBALS['timberContext']; if ( ! isset( $timberContext ) ) { throw new Exception( 'Timber context not set in footer.' ); } $args = array( 'posts_per_page' => 3, ); $timberContext['featured'] = new TimberPostQuery($args); $templates = array( 'page-plugin.twig'); $timberContext['content'] = ob_get_contents(); ob_end_clean(); Timber::render( $templates, $timberContext );
And inside my footer.twig I tried displaying them:
<ul class = "featured-posts-list"> {% for post in featured %} <li><a href="{{ post.link }}">{{ post.title }}</a></li> {% endfor %} </ul>
Now the problem is it displays nothing. If I replace featured with posts in footer.twig, it displays whatever posts are on the current page. It seems to me that Timber doesn’t process my post query and I don’t know why is that. I was looking for an answer but didn’t find one. Also, this is my first post here, so I am sorry in advance if it is confusing.
Advertisement
Answer
So, I just found the answer to my own question 🙂 In case someone has a similar problem, I resolved it by adding the variable to the context inside functions.php:
public function add_to_context( $context ) { //...previous variables... //the one I have added $context['featured'] = new TimberPostQuery(array( 'post_type' => 'post', 'posts_per_page' => 3, )); return $context; }
Then inside my footer.twig I use it like this:
<ul class = "featured-posts-list"> {% for post in featured %} <li><a href="{{ post.link }}">{{ post.title }}</a></li> {% endfor %} </ul>