我如何使用 Timber 在页脚中显示 3 个最近的帖子?

How do I display 3 recent posts in footer with Timber?

所以,我为此苦思冥想了 2 天。如何使用 Timber 和 Twig 在页脚中显示最近的 3 个 post?我正在使用 Timber 的入门主题。 我在 footer.php 文件中做了什么:

$timberContext = $GLOBALS['timberContext'];
if ( ! isset( $timberContext ) ) {
throw new \Exception( 'Timber context not set in footer.' );
}
$args = array(
'posts_per_page' => 3,
);
$timberContext['featured'] = new Timber\PostQuery($args);
$templates = array( 'page-plugin.twig');
$timberContext['content'] = ob_get_contents();
ob_end_clean();
Timber::render( $templates, $timberContext );

在我的 footer.twig 中,我尝试显示它们:

<ul class = "featured-posts-list">
    {% for post in featured %}
        <li><a href="{{ post.link }}">{{ post.title }}</a></li>
    {% endfor %}
</ul>

现在的问题是什么都不显示。如果我用 footer.twig 中的 posts 替换 featured,它会显示当前页面上的任何 posts。在我看来,Timber 不处理我的 post 查询,我不知道为什么会这样。我一直在寻找答案,但没有找到。另外,这是我第一次post来这里,所以如果造成混淆,请提前道歉。

所以,我刚刚找到了我自己问题的答案 :) 如果有人有类似的问题,我通过将变量添加到 functions.php:

中的上下文来解决它
public function add_to_context( $context ) {
        //...previous variables...
        //the one I have added
        $context['featured'] = new Timber\PostQuery(array(
            'post_type' => 'post',
            'posts_per_page' => 3,
        ));
        return $context;
    }

然后在我的 footer.twig 中,我这样使用它:

<ul class = "featured-posts-list">
    {% for post in featured %}
        <li><a href="{{ post.link }}">{{ post.title }}</a></li>
    {% endfor %}
</ul>