Timber Twig显示与类别相关的帖子

Timber和Twig的总菜鸟 . 我使用Timber和Twig的高级自定义字段 . 在自定义字段中,我有一个字段,允许用户通过术语对象的返回值通过分类字段类型检查任何类别中的3 .

我要做的是显示用户选择的任何类别中的3个以及下面该类别中的3个相关帖子 . 我总共有14个类别 .

看起来像这样

enter image description here

在我的PHP文件中

$context['categories'] = Timber::get_terms('category');

在我的Twig文件中:


```xml
{% 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 %}
```

上面的代码吐出了类别 Headers ,这很好但我很难搞清楚如何显示属于它的帖子 . 任何帮助,将不胜感激!!!

 **Edit:** 我写了这个查询(我不知道我在做什么) . 它拉了帖子,但只是重复 . 抱歉把问题放在gitgub上 .  :)

PHP

```java
$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);
```

枝条

```xml
{% 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 %}
```

回答(2)

3 years ago

所以这里的功能将......

  • 编辑器创建帖子并从静态首页上的ACF("featured topics")字段中选择3个类别

  • 在首页上,用户将看到三个选定的类别

  • 在每个类别下,用户可以看到与该类别相关的三个其他帖子(总共9个帖子)

home.php

$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);

home.twig

{% 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 %}

3 years ago

你需要创建一个 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);

枝条

{% 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 %}