Ale*_*lex 1 wordpress custom-taxonomy
我有一个自定义的“位置”分类法,有 3 个级别:城市 -> 地区 -> 郊区。
在访问已标记为城市、地区和郊区的单个帖子时,我还想检索附近的帖子。这意味着,同一郊区的其他职位。
这给了我分配给帖子的所有位置术语:
$terms = wp_get_post_terms( $wp_query->post->ID, 'location' );
Run Code Online (Sandbox Code Playgroud)
我发现如果一个术语的父级等于 0,则它是一个城市(顶级)。
foreach ( $terms as $term ) {
if ( $term->parent == 0 ) {
//$term is a city
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:我如何确定哪个术语是郊区(最低级别)?
我通过计算每个术语的祖先来解决这个问题。
使用函数 get_ancestors() 可以获得一个数组,其中包含层次结构中从最低到最高的父级。
这对我有用:
$terms = wp_get_post_terms( get_queried_object_id(), 'location', array( 'orderby' => 'id', 'order' => 'DESC' ) );
$deepestTerm = false;
$maxDepth = -1;
foreach ($terms as $term) {
$ancestors = get_ancestors( $term->term_id, 'location' );
$termDepth = count($ancestors);
if ($termDepth > $maxDepth) {
$deepestTerm = $term;
$maxDepth = $termDepth;
}
}
echo '<pre>';
print_r($deepestTerm);
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)