Timber Wordpress在每个类别中显示帖子

时间:2016-12-28 16:55:53

标签: wordpress twig timber

我在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是每个帖子的预览。

2 个答案:

答案 0 :(得分:2)

首先,@ jandon感谢您在StackOverflow上询问这些内容(而不是使用支持Q来弥补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 %}

答案 1 :(得分:1)

可能是一个错字:

{% for child_post in term.posts %}

而不是:

{% for child_post in terms.posts %}