Timber和Twig的总菜鸟。我使用Timber和Twig的高级自定义字段。在自定义字段中,我有一个字段,允许用户通过分类字段类型和term对象的返回值来检查任何类别中的3。
我要做的是显示用户选择的任何类别中的3个以及下面该类别中的3个相关帖子。我总共有14个类别。
看起来像这样
在我的PHP文件中,我有
$context['categories'] = Timber::get_terms('category');
在我的Twig文件中:
````
{% for featured_topic in post.get_field('featured_topics') %}
<div class="col-md-4 featured-topics-widget">
<h4>{{featured_topic.name}}</h4>
<ul>
{% for topic in topic_post %}
<li>{{topic.title}}</li>
{% endfor %}
</ul>
</div>
{% endfor %}
上面的代码吐出了类别标题,这很好但我很难搞清楚如何显示属于它的帖子。任何帮助将不胜感激!!!
编辑:我写了这个查询(我不知道我在做什么)。它拉了帖子,但只是重复。抱歉把问题放在gitgub上。 :)
PHP
$topic_args = array(
'post_type' => 'post',
'posts_per_page' => 3,
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => array( 81, 92, 82, 1, 88, 86, 85)
)
)
);
$context['topic_post'] = Timber::get_posts($topic_args);
TWIG
{% for featured_topic in post.get_field('featured_topics') %}
<div class="col-md-4 featured-topics-widget">
<h4>{{featured_topic.name}}</h4>
<ul>
{% for cat in topic_post.posts('category') %}
<li><a href="{{ cat.link }}">{{cat.name}}</a></li>
{% endfor %}
</ul>
</div>
{% endfor %}
答案 0 :(得分:1)
所以这里的功能将......
$featured_topic_ids = get_field('featured_topics');
// you may need to adjust this based on your ACF setup.
// Basically you're trying to get to an array of category IDs,
// then pass the resulting array to Timber::get_terms();
$context['featured_topics'] = Timber::get_terms($featured_topic_ids);
Timber::render('home.twig', $context);
{% for ft in featured_topics %}
<h4>{{ ft.name }}</h4>
{% for catpost in ft.posts(3) %}
<li><a href="{{ catpost.link }}">{{ catpost.title }}</a></li>
{% endfor %}
答案 1 :(得分:0)
您需要创建一个grouped
数组
PHP
$context['categories'] = Timber::get_terms('category');
$context['posts_per_category'] = [];
foreach($context['categories'] as $category) $context=['posts_per_category'][$category->ID] = Timber::get_posts('cat='.$category->ID);
Twig
{% for cat in categories %}
<li>
<a href="{{cat.link}}">{{cat.name}}</a>
<ul>
{% for post in posts_per_category[cat.ID] %}
<li>... Do sthing with post ...</li>
{% endfor %}
</ul>
</li>
{% endfor %}