问题描述
我有什么
Properties -- Property 1 -- Property 1.1 -- Property 1.1.1 and so on ... -- Property 2 -- Property 2.1 -- Property 2.1.1 ... -- Property 2.2 -- Property 2.2.1 ... -- Property 3 ...
我需要达到的结果
按级别获取条款。 费:
- 如果级别 = 1。预期结果
Property 1 Property 2 Property 3 ...
- 如果级别 = 2。预期结果
Property 1.1 Property 2.1 Property 2.2 Property 3.1 ...
- 如果级别 = 3。预期结果
Property 1.1.1 Property 2.1.1 Property 2.2.1 Property 3.1.1 ...
使用 get_terms
函数不允许按级别获取术语。
我需要一些函数或知道按级别获取术语的方法。
function get_terms_by_level($level) {
/// ... ?
}
解决方法
编辑
关注您的评论。如果您知道哪些是哪些,您可以随时使用 get_term_children()
。
$heirs = get_term_children( 'your-term-slug',$taxonomy );
var_dump( $heirs );
foreach ( $heirs as $key => $value ) {
echo $value;
};
要实现这种结构,您需要将查询视为 matryoshka doll。
您查询第一级分类术语,然后在处于第一级时继续查询第二级,依此类推...
<?php $taxonomy = 'custom-taxonomy-slug';
$first_level_terms = get_terms( $taxonomy,[
'parent' => 0,'hide_empty' => false,'title_li' => '',] );
if ( $first_level_terms ) {
foreach ( $first_level_terms as $first_level_term ) {
$second_level_terms = get_terms( [
'taxonomy' => $taxonomy,'child_of' => $first_level_term->term_id,'parent' => $first_level_term->term_id,] );
if ( $second_level_terms ) {
echo '<ul>';
foreach ( $second_level_terms as $second_level_term ) {
echo '<li>' . $second_level_term->slug . '</li>';
};
echo '</ul>';
};
};
}; ?>