Having a custom post type 'pubs' with custom taxonomy 'types' in which admin enter parent terms and their child terms. Using this code to get all the terms of current post type:
$object_terms = wp_get_object_terms($post->ID, 'types', array('fields' => 'all'));
if ($object_terms) {
echo '' . '' . '' ;
$res = '';
foreach ($object_terms as $term) {
$res .= $term->name . ',';
}
echo rtrim($res,' ,').'' . '';
}
this code displays both parent & child terms. Is there any way to exclude parent terms from the result? I need the code to display only child terms related to the current post.
未经测试,但我认为,如果将以下内容放在顶部的foreach循环中,则只会得到孩子:
if ($term->parent == 0) continue;
Just for someone still looking:
Solution is for when you have multiple level of hierarchy and you want just last level.
$term_array = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
foreach ($term_array as $term_id){
$children=get_term_children($term_id, $taxonomy);
if(empty($children)){
$exclude=$term_id;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.