mfos
mfos

Reputation: 111

Timber - list categories and their posts

I have a CPT ('vehicles') with custom taxonomy ('vehicles_category')

I have 4 categories (construction, road, waste, other) with numerous posts assigned to each of these categories.

I'm trying to list out each category with the posts assigned to them underneath so..

Construction
     Post 1    
     Post 2     
     etc
Road
     Post 6
     Post 9
     etc

Been battling with this.

I have this to get the posts...

$context['vehicles'] = Timber::get_posts([
    'order'     => 'ASC',
    'post_type' => 'vehicles',
    'posts_per_page' => -1,
    'paged' => $paged,
]);

and this to get the categories...

$context['categories'] = Timber::get_terms('vehicle_category');
$context['posts'] = $context['vehicles'];

So far i have this in my twig file...

{% for category in categories %}
    {% if category.count >= 1 %}
        <li>
            <a href="{{site.url}}/vehicles/{{ category.slug }}">{{ category.title }}</a>
        </li>
    {% endif %}
{% endfor %}

But it only outputs the categories as I'm missing the bit to output the posts but everything I try doesn't work.

Any ideas? Thanks

Upvotes: 3

Views: 10107

Answers (1)

mfos
mfos

Reputation: 111

Ok, really overthought this so stepped back a bit.

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

vehicle_category is my custom taxonomy.

{% for category in categories %}
    <h1>{{category.name}}</h1>

    <div class="c-vehicle--list">

                {% for post in category.posts %}
                    <div class="c-vehicle--list__item">

                            <a href="{{ site.url }}/vehicles/{{ post.slug }}" title="{{ post.title }}">
                                <img src="{{TimberImage(post.vehicle_image).src('postMedium')}}" alt="{{ post.title }}">
                                <span>{{ post.title }}</span>
                                <span>{{ post.terms('vehicle_category') | join(', ') }}</span>
                            </a>

                    </div>
                {% endfor %}
    </div>
{% endfor %}

So simply loop out the categories in my custom taxonomy and then list the posts post in category.post associated with that category.

Upvotes: 7

Related Questions