wordpress - Timber 获取类别及其子项的列表
问题描述
我在一个项目中使用木材,我在谷歌上搜索了我的需求但没有成功:我想循环类别及其各自的子项:
// inside my shortcode
...
$context['categories'] = get_categories(['hide_empty'=>false, 'parent'=> 20]);
return \Timber::compile( MY_DIR_PATH . '/views/preferences.twig', $context );
// inside the view (preferences.twig)
{% for category in categories %}
// Here how i get children of this current category ?
{% for child in function('get_categories',{'hide_empty': 'false', 'parent': category.term_id }) %}
{% endfor %}
{% endfor %}
从上面的代码中,我可以成功输出每个类别的父类别,但是在第二个循环中,我不知道如何根据父类别列出子类别:category.term_id
我从木材文档中搜索过,但没有办法,有人有建议吗?谢谢你
解决方案
在之前的项目中,我在我的 php 中构建了嵌套的类别父/子数据,然后将构建的数据数组传递给木材,请参见下面的示例:
function get_sorted_categories() {
// Get categories
$cat_args = array(
'hide_empty'=>false,
'parent'=> 20
);
$categories = get_categories( $cat_args );
if ( $categories ) {
// Store category heirarchy
$cat_data = array();
// build data array.
foreach ( $categories as $cat ) {
$cat_data[ $cat->term_id ] = array(
'name' => $cat->cat_name,
'snippet' => $cat->cat_description,
'link' => get_category_link( $cat->term_id ),
'children' => array(),
);
// Child categories
$cat_args_child = array(
'hide_empty'=>false,
'parent'=> $cat->term_id
);
$child_categories = get_categories( $cat_args_child );
if ( $child_categories ) {
foreach ( $child_categories as $child_cat ) {
$cat_data[ $cat->term_id ]['children'][] = array(
'name' => $child_cat->cat_name,
'snippet' => $child_cat->cat_description,
'link' => get_category_link( $child_cat->term_id ),
);
}
}
}
return $cat_data;
}
return false
}