I have the following WordPress query code working in my Timber theme, but am struggling with how to convert into the Timber/Twig format.
$args = array(
'taxonomy' => 'category',
'parent' => '7',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
);
$terms = get_terms( $args );
foreach ( $terms as $term ) {
$termId = $term->term_id;
// Output first level of children of parent category ID 7
echo '<p>' . $term->name . '</p>';
$args = array(
'taxonomy' => 'category',
'child_of' => $termId,
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
);
$childTerms = get_terms( $args );
foreach ( $childTerms as $childTerm ) {
$childTermId = $childTerm->term_id;
// Output second level of children of parent category ID 7
echo '<p>' . $childTerm->name . '</p>';
$args = array(
'cat' => $childTermId,
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
while( $query->have_posts() ) : $query->the_post();
// Output posts assigned to second level children categories
echo '<p><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></p>';
endwhile;
wp_reset_postdata();
// $posts = Timber::get_posts( $args );
}
}
Example Timber/Twig code with incomplete functionality
{% for term in terms %}
<div class="category">
<h3>
{{ term.name }}
</h3>
{% for childTerm in terms %}
{% if childTerm.parent == term.term_id %}
<div class="category__child">
<h4>{{ childTerm.name }}</h4>
<!-- Output posts from child terms here -->
</div>
{% endif %}
{% endfor %}
</div>
{% endfor %}
HTML nested output example
Parent Category
- Child Category
- Post Title and excerpt
- Post Title and excerpt
- Post Title and excerpt
- Child Category
- Post Title and excerpt
- Post Title and excerpt
- Post Title and excerpt
Parent Category
- Child Category
- Post Title and excerpt
- Post Title and excerpt
- Post Title and excerpt
Parent Category
- Child Category
- Post Title and excerpt
- Post Title and excerpt
- Post Title and excerpt
Any assistance is greatly appreciated.