Reputation: 77
I have a custom post type called products and custom taxonomy called type.
I need to show the list of types and inside three post from each one. Like this
Chicken
{Chicken description} | Three posts from products in the chicken type
Pork
{Pork description} | Three posts from products in the pork type
And so for like 6 product types.
So I have this in my wordpress .php file
$terms = get_terms('tipo', array('orderby' => 'id'));
foreach ($terms as $term) {
$args = array(
'post_type' => 'producto',
'tax_query' => array(
array(
'taxonomy' => 'tipo',
'field' => 'slug',
'terms' => $term->slug,
),
),
);
$context['product_'.$term->slug] = Timber::get_posts($args);
}
$context['cats'] = Timber::get_terms('tipo', array('orderby' => 'id'));
Which should get me product_pork and product_chicken and all else
Inside the .twig
file I have this
{% for cat in cats %}
{{cat.title}}
{{cat.description}}
{% endfor %}
And everything is fine up until that point but then when I try to do this
{% for cat in cats %}
{{cat.title}}
{{cat.description}}
{% for product in cat.slug %}
{{product.title}}
{% endfor %}
{% endfor %}
I get nothing but if I try this
{% for cat in cats %}
{{cat.title}}
{{cat.description}}
{% for product in product_pork %}
{{product.title}}
{% endfor %}
{% endfor %}
Of course it works, my question is, is there a way to make it work? Or do you think of another way entirely different? I'm open to suggestions
Thanks a lot
Upvotes: 2
Views: 3094
Reputation: 1734
The problem is in this line...
{% for product in cat.slug %}
cat.slug
is a string, so there's no way to iterate through it. Try this code...
$terms = get_terms('tipo', array('orderby' => 'id'));
foreach ($terms as &$term) {
$args = array(
'post_type' => 'producto',
'tax_query' => array(
array(
'taxonomy' => 'tipo',
'field' => 'slug',
'terms' => $term->slug,
),
),
);
$term->products = Timber::get_posts($args);
}
$context['cats'] = $terms;
{% for cat in cats %}
{{cat.title}}
{{cat.description}}
{% for product in cat.products %}
{{product.title}}
{% endfor %}
{% endfor %}
Upvotes: 3