Timber Wordpress 在每个类别中显示 post

Timber Wordpress display post in each category

我在 Wordpress 中使用 Timber 插件。我想创建一个循环,在每个类别中显示 4 篇文章。

publications.php

$context = Timber::get_context();
$post = new TimberPost();

$cat_id = wp_get_post_categories($post->ID);
$context['each_cat'] = Timber::get_posts(array('cat' => $cat_id[0], 'posts_per_page' => 4));

Timber::render( array( 'publications.twig', 'page.twig' ), $context );

publications.twig

{% for category in each_cat %}
<h2 class="title">{{category.name}}</h2>
    <article class="article--box">
        {% include "bloc_preview.twig" %}
    </article>
{% endfor %}

包含 bloc_preview.twig 是每个 post 的预览。

首先,@jandon 感谢您在 Whosebug 上提出这些问题(而不是通过支持 Qs 混淆 GitHub 问题)。完成您要查找的内容的最简单方法是使用 .posts method on your term objects。根据您的示例,您可以在 Twig 中完成所有这些...

publications.twig

<h2>{{ post.title }}</h2>
<h3>Related Posts</h3>
{% for term in post.terms('category') %}
    <h3>Related Posts in {{ term.name }}</h3>
    <ul>
        {% for child_post in term.posts(4) %}
        <li><a href="{{ child_post.link }}">{{ child_post.title }}</a></li>
        {% endfor %}
    </ul>
{% endfor %}

可能是它适用的拼写错误:

{% for child_post in term.posts %}

而不是:

{% for child_post in terms.posts %}