Timber Twig Show Posts Associated with Category

大憨熊 提交于 2019-12-02 08:13:17

So here is functionality that will...

  • Editor creates post and selects 3 categories from an ACF ("featured topics") field on a static front page
  • On the front page, a user will see three selected categories
  • Under each category the user sees three OTHER posts associated with that category (so 9 posts total)

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

You need to create a grouped array,

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 %}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!