1

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

出版物.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 );

出版物.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是每个帖子的预览。

4

2 回答 2

2

首先,@jandon 感谢您在 StackOverflow 上提出这些问题(而不是将 GitHub 问题与支持 Qs 混为一谈)。完成您正在寻找的最简单的方法是.posts在您的术语 objects 上使用该方法。根据您的示例,您可以在 Twig 中完成所有操作...

出版物.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 %}
于 2016-12-28T20:17:56.377 回答
1

可能是它适用的错字:

{% for child_post in term.posts %}

代替:

{% for child_post in terms.posts %}
于 2017-05-23T07:28:34.400 回答